7

I need to implement range constraints on Entity data fields:

@Entity
@Table(name = "T_PAYMENT")
public class Payment extends AbstractEntity {

    //....

    //Something like that
    @Range(minValue = 80, maxValue = 85)
    private Long paymentType;

}

I already created validating service, but have to implement many of these cases.

I need the app to throw exception if the inserted number is out of range.

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
J-Alex
  • 6,881
  • 10
  • 46
  • 64
  • 1
    You can define range using following annotation. `@Max(85) @Min(5)` and if you want define custom messages for this validation then you need to create custom constraints. Refer this [link](http://www.thejavageek.com/2014/05/24/jpa-constraints/) – ypp Jun 13 '16 at 05:37
  • http://stackoverflow.com/questions/5129825/difference-between-max-and-decimalmax-and-min-and-decimalmin – Piyush Aghera Jun 13 '16 at 05:55

4 Answers4

9

You need Hibernate Validator (see documentation)

Hibernate Validator

The Bean Validation reference implementation.

Application layer agnostic validation Hibernate Validator allows to express and validate application constraints. The default metadata source are annotations, with the ability to override and extend through the use of XML. It is not tied to a specific application tier or programming model and is available for both server and client application programming. But a simple example says more than 1000 words:

public class Car {

   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   // ...
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
2

With hibernate-validator dependency you can define range check

@Min(value = 80)
@Max(value = 85)
private Long paymentType;

In pom.xml add below dependency

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>{hibernate.version}</version>
    </dependency>
Saravana
  • 12,647
  • 2
  • 39
  • 57
2

I believe this is the specific annotation you are looking for: https://docs.jboss.org/hibernate/validator/4.1/api/org/hibernate/validator/constraints/Range.html

Example:

@Range(min = 1, max =12)
private String expiryMonth;

This is also a more beneficial annotation because it will work on Strings or Number variants without using two annotations like is the case with @Max/@Min. @Size is not compatible with Integers.

dadams89
  • 21
  • 1
1

For integer and long you can use @Min(value = 80) @Max(value = 85)

For BigDecimal @DecimalMin(value = "80.99999") @DecimalMax(value = "86.9999")