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.
The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean. Constraints can be built in or user defined. User-defined constraints are called custom constraints.
The @NotNull Annotation is, actually, an explicit contract declaring the following: A method should not return null. A variable (like fields, local variables, and parameters) cannot should not hold null value.
constraints Description. Contains all the Bean Validation provided constraints also called built-in constraints. These constraints do not cover all functional use cases but do represent all the fundamental blocks to express low level constraints on basic JDK types.
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; // ... }
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>
For integer and long you can use @Min(value = 80)
@Max(value = 85)
For BigDecimal @DecimalMin(value = "80.99999")
@DecimalMax(value = "86.9999")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With