This article demonstrates how constraints can be used along with jpa bean validation and how constraints can be retrieved when doing jpa bean validation.
JPA Bean Validation:
JPA bean validation isn’t directly related to JPA itself. Package javax.validation.constraints provides a way to validate a java bean using constraints which we can use for jpa bean validation. When constraints are applied to a bean, validator needs to be invoked. It can be done in following ways.
In Container Environment:
JPA bean validation can be done in java EE environment using container managed validator. It is retrieved using @Resource annotation as shown below.
In JavaSE Environment:
Validator can be retrieved in a simple javaSE environment using code below.
JPA Bean Validation Example:
Now that we know how to retrieve a Validator instance, let us see a jpa bean validation example. We have an employee entity as below.
Let us try jpa bean validation now.
This produces output as below
salary must be less than or equal to 50000.00
lastName may not be null
Let us see what each line does:
- creates validator factory from default implementation available that you have provided in a jar file.
- gets validator instance from factory.
- ConstraintViolation. performs validation on employee entity and returns a Set of
- and return the name of property for which validation failed and corresponding message.
I hope this jpa bean validation example helped understand how beans can be validated.
References for further study :