JPA Bean Validation

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

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.

Note that @NotNull means null value is not allowed for firstName, lastName and salary and @DecimalMax means salary cannot be greater than 50000.

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:

  • Validation.buildDefaultValidatorFactory(); creates validator factory from default implementation available that you have provided in a jar file.
  • Validator validator = factory.getValidator();  gets validator instance from factory.
  • validator.validate(employee);  performs validation on employee entity and returns a Set of ConstraintViolation.
  • constraint.getPropertyPath();  and constraint.getMessage(); 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 :

 

 

Share Button

1 comment for “JPA Bean Validation

Leave a Reply

Your email address will not be published. Required fields are marked *