March 1, 2021
Hot Topics:

Bean Validation in Hibernate and JPA 2

  • By Sangeetha S, Nitin KL
  • Send Email »
  • More Articles »

A typical multi-tier Java application requires data validation at various layers, from the client tier to the database tier. Rather than duplicate the validation logic across all the application tiers, object relational mapping (ORM) technologies such as the Java Persistence API (JPA) and Hibernate keep the validation logic in the domain model using Bean validation (JSR-303). Bean validation specifies a metamodel and an API for validating entities, generally by using annotations that can be applied at the field, method or class level.

Specifically, the javax.validation.constraints package defines a set of built-in annotations for validation, while custom annotations can also be used to specify the constraints. Some of the standard annotations defined in this package are @NotNull, @Min, @Max, @Size and @Pattern. When constraints are applied to a class that implements an interface or extends a class, the validation is applied to its parent object as well. Here are constraints applied to a class at the field level:

import javax.validation.constraints.Min;import javax.validation.constraints.Max;import javax.validation.constraints.NotNull;import javax.validation.constraints.Size;public class Employee {   @NotNullprivate Integer id;private String fname;private String lname;@Size(min = 24, max = 30)private Integer age;@Min(1)private Integer experience;@Max(200000)private Integer salary;// other methods.}

In this article, we explain how Hibernate Validator -- the reference implementation of JSR 303 -- handles Bean validation and then for comparison present a brief discussion of JPA 2's Bean validation.

Bean Validation in Action

Bean validation allows developers to validate an entire object graph by using the @Valid annotation, by which all the reference objects with @Valid get validated when the parent object is validated. With an object graph, any collection-type object also gets validated.

A developer can validate an instance by first obtaining a Validator instance, which can be obtained via ValidatorFactory as shown below:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();Validator validator = factory.getValidator();

The Validator interface contains the following methods:

  • validate() -- used to validate all the constraints on the class
  • validateProperty() -- used to validate the property of a given object
  • validateValue() -- checks whether a single property of a class can be validated, provided the property with the specified value

Page 1 of 2

This article was originally published on August 5, 2010

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date