Login:  Password:    
forgot my password
sign up!
Search: 

Knowing the Hibernate Validator - Part 1

Learning the Hibernate Validator, which implements the JSR 303 - Bean Validation API, and allows the validation of the data in objects

1 0

About the article:

This article introduces the Hibernate Validator, reference implementation of JSR 303 - Bean Validation API. This API allows you to easily validate, class objects that represent the application domain.

What is it for?

This article introduces developers to the Hibernate Validator API, which allows to incorporate data validation from the application through an easy to use and customizable API.

When this subject is useful:

Developers who want to learn how the Hibernate Validator works and how to integrate it into their applications will find detailed explanations in this article on how this API works.

Knowing the Hibernate Validator:

The Bean Validation API, represented by the JSR 303 was released in December 2009. Hibernate Validator has emerged as the reference implementation of this API and lets you use annotations to validate data quickly and easily. The biggest advantage is that the Bean Validation API is independent of the application layer where it is used and even in the way it is coded, allowing it to be used in various scenarios. This article discusses in detail how the Hibernate Validator works.

 

 In December 2009, the final version of JSR 303 was released. It's about the Bean Validation API that allows quickly and easily data validation through the use of annotations. The purpose of this JSR is the validation of the data present in the classes that model the application domain, which usually follow the standard JavaBeans. What's interesting is that the Bean Validation API is independent of the application layer where it is used and even the way of how we code it. It can be used in both desktop and web applications, and isn't tied to the persistence mechanism used. Thus, can be used in various scenarios.

Data validation was always present in systems that receive input from the user. Each framework implements a proprietary mechanism to validate the information, which created incompatibility problems and was harder to integrate.

With the advent of JSR 303 has established a standard API for validation, which is flexible enough to be used for many different types of frameworks. In addition, the Bean Validation API provides data validation classes in the application domain, which is simpler than when the process is done by layer. In the layer validation, it is necessary to verify the same data several times (in the presentation layer, business, persistence, etc.). In order to ensure information consistency. By validating the data directly in the domain classes, the whole process is centralized, therefore the objects of these classes typically runs thru the application layers.

The JSR 303 implementation reference is the Hibernate Validator, which will be explained in detail throughout this article.

Configuring Hibernate Validator

To work with the API you must use Java version 5 or higher, since the Hibernate Validator is not compatible with earlier versions of JDK. Setting the application to use the API is simple. The first step is to download from the project official website, which can be found in the reference section. The version available until the time of this writing is 4.1.0.

After unpacking the file (which can be downloaded in ZIP or TGZ format), simply add the following JARs in your application's classpath: hibernate-validator-4.1.0.Final.jar, log4j-1.2.14.jar, slf4j-api-1.5.6.jar, slf4j-log4j12-1.5.6.jar and validation-api-1.0.0.Ga.jar.They are all inside of the downloaded compressed file. If your application use Java 5 instead of 6, you must also add the API JAXB JARs: JAXB-api-2.2.jar and JAXB-impl-2.1.12.jar.This set of files is the minimum necessary to set the Hibernate Validator to work.

Setting constraints using annotations

The constraints are used to define rules regarding the data of an object. You can, for example, define that a particular attribute can not be null or that a value of a numeric attribute must be within a defined interval. When the data validation process is performed, a verification is made to check if the data are consistent with the established rules.

When you need to add validation constraints in the code, this is done through the use of annotations. Hibernate Validator comes with a set of annotations for common validations, although the API allows the programmer to make customizations. The creation of custom constraints will be addressed later in this article.

There are two places where constraints may apply. The first is directly in the class attribute. In this case the Java directly accesses the attribute thru reflection in order to do the validation. Listing 1 shows an example. The second form of implementation of constraints can be used when the class follows the specification of a JavaBean. In this case you can use the annotation on the getter method of the attribute. Listing 2 shows how this can be done. You must choose only one option, because if both are used the validation will be done twice.

 

Listing 1.Using the constraint @NotNull on the attribute.

public class Student {

 

  @NotNull

  private String name;

}

 

Listing 2.Using the constraint @NotNull on the getter method.

public class Student {

 

  @NotNull

  public String getName () {

    return name;

  }

}

All elements of the Hibernate Validator (classes, interfaces, annotations, etc..) Used by your code belong to the package javax.validation.

In addition to the annotation @NotNull shown in the example, which verifies that the data is not null, there are other important annotations included in Hibernate Validator. Following we are going to discuss some of them in more details. For more information about these and other annotations, refer to JSR 303 and the Hibernate Validator documentation.

@AssertFalse and @AssertTrue

These annotations validate if the data is true or false, respectively. Should be implemented in Boolean data (the primitive type Boolean and Boolean class are supported).Listing 3 shows both constraints. The attribute hasWarnings shall be false while fullAge must be true.

 

Listing 3.Using the annotations @AssertTrue and @AssertFalse.

public class Student {

 

  @AssertFalse

  private boolean hasWarning;

 

  @AssertTrue

  private boolean fullAge;

}

@Max and @Min

These annotations validate if in a given numeric data has a minimum or maximum value, respectively. Are applied to data types BigDecimal, BigInteger, String, byte, short, long, and their corresponding classes wrappers. Listing 4 shows an example where the attribute grade should have a minimum value equal to 70 and maximum of 100.This example shows that it is possible to use more than one constraint for the same attribute or getter method.

 

Listing 4.Using the annotations @Min and @Max.

public class Student {

 

  @Min (70)

  @Max (100)

  private int grade;

}

@Size

Validate if the data size is between the values ​​specified in the attributes min and max (including).This annotation can be applied to String objects, arrays and objects of type Collection and Map. Listing 5 shows an example where the attribute street (String type) must have a minimum 10 and maximum of 50 characters.

 

Listing 5.Using the annotation @Size.

{public class StudentAddress

 

  @Size (min = 10, max = 50)

  private String street;

}

@Pattern

This annotation allows data validation according to a regular expression, which is specified by the regexp attribute. Works with String data type. Listing 6 shows how to use it to validate a ZIP code.

 

Listing 6.Using the @Pattern annotation.

{public class StudentAddress

 

  @Pattern (regexp = "[0-9] {5} - [0-9] {3}")

  private String zip;

}

@Valid

It is quite common to find classes that have attributes that reference other classes. In these situations, it is often interesting to validate not only a specific object, but also all the objects referenced by it. This is the role of the @Valid annotation. When it is present, Hibernate Validator performs the necessary validations on the object being referenced. Listing 7 shows an example where, by invoking the validation of an object of the class Student, the object of the class StudentAddress will be validated also in cascade. In this case, if the attribute street from the address is null, the validation will fail.

 

Listing 7.Using the @Valid annotation.

public class Student {

 

  @Valid

  private StudentAddress address;

}

 

{public class StudentAddress

 

  @NotNull

  private String street;

}

 

Invoking the validation process

After the constraints definition in the form of annotations, the next step is to invoke the code that will actually do the data validation in accordance with the rules that were established.

For this, the first required object is an instance of ValidatorFactory, which will be used to construct an object of type Validator. The typical code to get a Validator object is shown in Listing 8.

 

Listing 8.Getting a Validator object.

ValidatorFactory Validation.buildDefaultValidatorFactory factory = ();

Validator validator = factory.getValidator ();

 

Having a reference to a validator object allows to invoke the validation. It can be done in different ways, which will be explained in detail in the sequel and will be based on the code in Listing 9.Note that the constraints are applied to the attribute name and in the method getGrade ().

 

Listing 9.Restrictions defined in the class Student.

public class Student {

 

  @NotNull

  @Size (max = 40)

  private String name;

 

  private int studentGrade;

 

  @Min (70)

  @Max (100)

  public int getGrade() {

    return studentGrade;

  }

}

 

The first option to invoke the validation process is to call the validate() method that receives as parameter the object to be validated. For an object student from the class Student, the call validator.validate(student) performs validation on the object in accordance with all constraints set.

The second option is to use the method validateProperty(). Unlike the validate() method, it allows to invoke the validation on only one object property. The property name provided is the name of the attribute (if the constraint is defined in the attribute) or the name that follows the specification of a JavaBean (if the constraint is defined in the method). By invoking the method validator.validateProperty(student, "name"), the validation will be invoked directly in the attribute name.But if invoked the method validator.validateProperty (student, "grade"), it will be invoked in the method getGrade().

The third and final option is to make a validation simulation using the method validateValue(). This way you can verify that the validation work for a property where a given value was attributed to it. To check whether the grade property of the student class could take the value 60, for example, simply invoke validator.validateValue (Student.class, "grade", 60).

When a superclass has constraints set and an object of its subclass is submitted for validation, the constraints of the superclass are also validated.

The three methods explained above (validate(), validateProperty() and validateValue()) returns a Set >. Through this collection you can see if there were validation problems and identify them. When there is none, Set returns empty.if one or more errors occur, each item stored on Set represents a validation error. Listing 10 shows an example of code that can be used to display in the command prompt window the validation errors occurred in the student object.

 

Listing 10.Displaying validation errors of the object in the command prompt window.

Set > errors = validator.validate(student);

 

for (ConstraintViolation error: errors) {

  String msgError = error.getMessage();

  System.out.println (msgError);

}

 

The getMessage() method is used to return the error message. This message is called interpolated, since it is generated based on a model (template). This article will address, next, how to work with the customization of error messages. Other useful methods are getInvalidValue() which returns the property value of the object that caused the validation problem, and getRootBean() which returns the reference of the object which validation failed.

The method validateValue() does not receive as a parameter an object to be validated.In this case the method getRootBean() returns null.


This article continues http://www.mrbool.com/articles/viewcomp.asp?comp=21878 

Mr.Bool Editor
Mr.Bool team writes articles to several sites on internet
Add your comment
[Fechar]

Este post é fechado - você precisa ter acesso ao post para incluir um comentário.


no comments have been posted - be the first!
Help us to improve! Give us your feedback:

Give your note to this post: 1 2 3 4 5 6 7 8 9 10
Is this post helpful? Yes No



[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits








mrbool.com
contact us   |   publish your post   |   buy credits

Copyright 2013 - all rights reserved to www.web-03.net