Wednesday, 29 August 2012

Hibernate Validator Examples

Let us some examples for Hibernate validator
Here is the introduction notes from the hibernate documentation
Bean Validation standardizes how to define and declare domain model level constraints. You can, for example, express that a property should never be null, that the account balance should be strictly positive, etc. These domain model constraints are declared in the bean itself by annotating its properties. Bean Validation can then read them and check for constraint violations. The validation mechanism can be executed in different layers in your application without having to duplicate any of these rules (presentation layer, data access layer). Following the DRY principle, Bean Validation and its reference implementation Hibernate Validator has been designed for that purpose.
The integration between Hibernate and Bean Validation works at two levels. First, it is able to check in-memory instances of a class for constraint violations. Second, it can apply the constraints to the Hibernate metamodel and incorporate them into the generated database schema.
Each constraint annotation is associated to a validator implementation responsible for checking the constraint on the entity instance. A validator can also (optionally) apply the constraint to the Hibernate metamodel, allowing Hibernate to generate DDL that expresses the constraint. With the appropriate event listener, you can execute the checking operation on inserts, updates and deletes done by Hibernate.
When checking instances at runtime, Hibernate Validator returns information about constraint violations in a set of ConstraintViolations. Among other information, the ConstraintViolation contains an error description message that can embed the parameter values bundle with the annotation (eg. size limit), and message strings that may be externalized to a ResourceBundle.
Example 1:
In the first example, we will see very basic not null constraint validation. Here is the Step by Step Tutorial.
Example 2:
In the second example, we will see some more constraint validation. Here is the Step by Step Tutorial.
Example 3:
In this example, we will see how we can create our custom constraint validation. Here is the Step by Step Tutorial.
Example 4:
In this example, we will see how we can create our custom constraint @Required. Here is the Step by Step Tutorial.
Example 5:
In this example, nothing is new, we will take care example 2 and will use the utility class to perform validationHere is the Step by Step Tutorial.

No comments:

Post a Comment