Skip to content

Quickstart - Spring Boot

Project Dependencies

To use the unit-api with Spring Boot you need to include the following dependencies to your pom.xml/build.gradle file:

implementation("com.raynigon.unit-api:jackson-starter:1.1.7")
implementation("com.raynigon.unit-api:jpa-starter:1.1.7")
<dependency>
    <groupId>com.raynigon.unit-api</groupId>
    <artifactId>jackson-starter</artifactId>
    <version>1.1.7</version>
</dependency>
<dependency>
    <groupId>com.raynigon.unit-api</groupId>
    <artifactId>jpa-starter</artifactId>
    <version>1.1.7</version>
</dependency>

If you use jdbc instead of jpa or no persistence layer at all skip the jpa-starter module.

Rest API Usage

You can declare your model like this:

public class BasicEntity {

    public String id;

    @JsonUnit(KilometrePerHour.class)
    public Quantity<Speed> speed;
}

Jackson will now accept any quantity and convert it to the given unit. The following examples will be accepted by Jackson:

{
  "id": "65bf1872-d197-4d72-9950-2b7b4d74a674",
  "speed": 80
}
{
  "id": "65bf1872-d197-4d72-9950-2b7b4d74a674",
  "speed": "80"
}
{
  "id": "65bf1872-d197-4d72-9950-2b7b4d74a674",
  "speed": "80 km/h"
}
{
  "id": "65bf1872-d197-4d72-9950-2b7b4d74a674",
  "speed": "22.2222 m/s"
}

Every example will result in having the speed property with a value of 80 and the unit "km/h".

Jpa Entity Usage

You can declare your entity like this:

@Entity
@Table("basic_entity")
@TypeDef(
        name = "quantity",
        typeClass = QuantityType.class,
        defaultForType = Quantity.class
)
public class BasicEntity {

    @Id
    @Column(name="id")
    public String id;

    @JpaUnit(KilometrePerHour.class)
    @Column(name="speed")
    public Quantity<Speed> speed;
}

You need to have the @TypeDef annotation due to a missing feature in hibernate (see here). Depending on the database you are using, you need to specify the columnDefinition property in the @Column annotation. By default, the value stored in the database will be a floating-point value. In this example the value will be saved in "km/h".

Springdoc Usage

To use the unit-api with springdoc you need to include the following dependencies to your pom.xml/build.gradle file:

implementation("com.raynigon.unit-api:springdoc-starter:1.1.7")
<dependency>
    <groupId>com.raynigon.unit-api</groupId>
    <artifactId>springdoc-starter</artifactId>
    <version>1.1.7</version>
</dependency>

Rebuild your application and check you swagger documentation generated by springdoc. (Usually located at http://localhost:8080/swagger-ui.html) The Examples will now contain a value with a valid unit foreach Quantity<?> property.