How to use Hibernate Validator in Spring MVC

how does hibernate validator work and how to use hibernate validator in spring and how to validate hibernate.cfg.xml and how to validate hibernate mapping
LexiWills Profile Pic
LexiWills,United Kingdom,Professional
Published Date:31-07-2017
Your Website URL(Optional)
Comment
Hibernate Validator JSR 303 Reference Implementation Reference Guide 4.3.2.Final by Hardy Ferentschik and Gunnar MorlingPreface ............................................................................................................................. v 1. Getting started ............................................................................................................. 1 1.1. Project set up ..................................................................................................... 1 1.2. Applying constraints ............................................................................................ 2 1.3. Validating constraints . ......................................................................................... 3 1.4. Where to go next? .............................................................................................. 5 2. Validation step by step . ............................................................................................... 7 2.1. Defining constraints . ........................................................................................... 7 2.1.1. Field-level constraints ............................................................................... 7 2.1.2. Property-level constraints .......................................................................... 8 2.1.3. Class-level constraints . ............................................................................. 9 2.1.4. Constraint inheritance . ............................................................................ 10 2.1.5. Object graphs . ....................................................................................... 11 2.2. Validating constraints ........................................................................................ 13 2.2.1. Obtaining a Validator instance . ............................................................... 13 2.2.2. Validator methods .................................................................................. 13 2.2.3. ConstraintViolation methods .................................................................... 15 2.2.4. Message interpolation ............................................................................. 15 2.3. Validating groups .............................................................................................. 16 2.3.1. Group sequences . .................................................................................. 19 2.3.2. Redefining the default group sequence of a class . .................................... 20 2.4. Built-in constraints ............................................................................................. 23 2.4.1. Bean Validation constraints . .................................................................... 23 2.4.2. Additional constraints .............................................................................. 27 3. Creating custom constraints ..................................................................................... 33 3.1. Creating a simple constraint .............................................................................. 33 3.1.1. The constraint annotation ....................................................................... 33 3.1.2. The constraint validator . ......................................................................... 35 3.1.3. The error message ................................................................................. 38 3.1.4. Using the constraint ............................................................................... 38 3.2. Constraint composition ...................................................................................... 40 4. XML configuration ..................................................................................................... 43 4.1. validation.xml .................................................................................................... 43 4.2. Mapping constraints .......................................................................................... 44 5. Bootstrapping . ........................................................................................................... 49 5.1. Configuration and ValidatorFactory .................................................................... 49 5.2. ValidationProviderResolver ................................................................................ 50 5.3. MessageInterpolator . ......................................................................................... 51 5.3.1. ResourceBundleLocator . ......................................................................... 52 5.4. TraversableResolver . ........................................................................................ 52 5.5. ConstraintValidatorFactory ................................................................................. 54 6. Metadata API . ............................................................................................................. 57 6.1. BeanDescriptor ................................................................................................. 57 6.2. PropertyDescriptor . ........................................................................................... 57 iiiHibernate Validator 6.3. ElementDescriptor ............................................................................................. 57 6.4. ConstraintDescriptor .......................................................................................... 58 7. Integration with other frameworks ............................................................................. 59 7.1. OSGi . ............................................................................................................... 59 7.2. Database schema-level validation . ..................................................................... 60 7.3. ORM integration . ............................................................................................... 60 7.3.1. Hibernate event-based validation ............................................................. 60 7.3.2. JPA ....................................................................................................... 62 7.4. Presentation layer validation .............................................................................. 62 8. Hibernate Validator Specifics .................................................................................... 65 8.1. Public API . ....................................................................................................... 65 8.2. Fail fast mode .................................................................................................. 67 8.3. Method validation .............................................................................................. 68 8.3.1. Defining method-level constraints ............................................................ 69 8.3.2. Evaluating method-level constraints ......................................................... 70 8.3.3. Retrieving method-level constraint meta data ........................................... 72 8.4. Programmatic constraint definition . ..................................................................... 73 8.5. Boolean composition for constraint composition .................................................. 75 9. Annotation Processor . ............................................................................................... 77 9.1. Prerequisites ..................................................................................................... 77 9.2. Features ........................................................................................................... 77 9.3. Options . ........................................................................................................... 78 9.4. Using the Annotation Processor ......................................................................... 78 9.4.1. Command line builds . ............................................................................. 78 9.4.2. IDE builds .............................................................................................. 81 9.5. Known issues . .................................................................................................. 83 10. Further reading ........................................................................................................ 85 ivPreface Validating data is a common task that occurs throughout any application, from the presentation layer to the persistence layer. Often the same validation logic is implemented in each layer, proving time consuming and error-prone. To avoid duplication of these validations in each layer, developers often bundle validation logic directly into the domain model, cluttering domain classes with validation code which is really metadata about the class itself. JSR 303 - Bean Validation - defines a metadata model and API for entity validation. The default metadata source is annotations, with the ability to override and extend the meta-data through the use of XML. The API is not tied to a specific application tier or programming model. It is specifically not tied to either the web tier or the persistence tier, and is available for both server-side application programming, as well as rich client Swing application developers. Hibernate Validator is the reference implementation of this JSR. The implementation itself as well as the Bean Validation API and TCK are all provided and distributed under the Apache Software License 2.0 http://www.apache.org/licenses/LICENSE-2.0. vviChapter 1. Getting started This chapter will show you how to get started with Hibernate Validator, the reference implementation (RI) of Bean Validation. For the following quickstart you need: • A JDK = 6 • Apache Maven http://maven.apache.org/ • An Internet connection (Maven has to download all required libraries) • A properly configured remote repository. Add the following to your settings.xml: Example 1.1. Configuring the JBoss Maven repository repositories repository idjboss-public-repository-group/id urlhttps://repository.jboss.org/nexus/content/groups/public-jboss/url releases enabledtrue/enabled /releases snapshots enabledtrue/enabled /snapshots /repository /repositories More information about settings.xml can be found in the Maven Local Settings Model http:// maven.apache.org/ref/2.0.8/maven-settings/settings.html. 1.1. Project set up In order to use Hibernate Validator within an existing Maven project, simply add the following dependency to your pom.xml: Example 1.2. Maven dependency of Hibernate Validator dependency groupIdorg.hibernate/groupId artifactIdhibernate-validator/artifactId version4.3.2.Final/version /dependency Alternatively, you can start by creating a sample project using Hibernate Validator's Quickstart Maven archetype as follows: 1Chapter 1. Getting started Example 1.3. Using Maven's archetype plugin to create a sample project using Hibernate Validator mvn archetype:generate -DarchetypeGroupId=org.hibernate \ -DarchetypeArtifactId=hibernate-validator-quickstart-archetype \ -DarchetypeVersion=4.3.2.Final \ -DarchetypeRepository=http://repository.jboss.org/nexus/content/ groups/public-jboss/ \ -DgroupId=com.mycompany \ -DartifactId=hv-quickstart Maven will create your project in the directory hv-quickstart. Change into this directory and run: mvn test Maven will compile the example code and run the implemented unit tests. Let's have a look at the actual code in the next section. Tip For the purposes of logging, Hibernate Validator uses the JBoss Logging API. This is an abstraction layer which supports several known logging solutions (e.g. log4j or the logging framework provided by the JDK) as implementation. Just add your preferred logging library to the classpath and all log requests from Hibernate Validator will automatically be delegated to that logging provider. Alternatively, you can explicitely specify a provider using the system property org.jboss.logging.provider. Supported values currently are jboss, jdk, log4j and slf4j. 1.2. Applying constraints Open the project in the IDE of your choice and have a look at the class Car: Example 1.4. Class Car annotated with constraints package com.mycompany; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Car NotNull 2Validating constraints private String manufacturer; NotNull Size(min = 2, max = 14) private String licensePlate; Min(2) private int seatCount; public Car(String manufacturer, String licencePlate, int seatCount) this.manufacturer = manufacturer; this.licensePlate = licencePlate; this.seatCount = seatCount; //getters and setters ... NotNull, Size and Min are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance: • manufacturer shall never be null • licensePlate shall never be null and must be between 2 and 14 characters long • seatCount shall be at least 2. 1.3. Validating constraints To perform a validation of these constraints, we use a Validator instance. Let's have a look at the CarTest class: Example 1.5. Class CarTest showing validation examples package com.mycompany; import static org.junit.Assert.; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.BeforeClass; import org.junit.Test; public class CarTest private static Validator validator; BeforeClass public static void setUp() 3Chapter 1. Getting started ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); Test public void manufacturerIsNull() Car car = new Car(null, "DD-AB-123", 4); SetConstraintViolationCar constraintViolations = validator.validate(car); assertEquals(1, constraintViolations.size()); assertEquals("may not be null", constraintViolations.iterator().next().getMessage()); Test public void licensePlateTooShort() Car car = new Car("Morris", "D", 4); SetConstraintViolationCar constraintViolations = validator.validate(car); assertEquals(1, constraintViolations.size()); assertEquals("size must be between 2 and 14", constraintViolations.iterator().next().getMessage()); Test public void seatCountTooLow() Car car = new Car("Morris", "DD-AB-123", 1); SetConstraintViolationCar constraintViolations = validator.validate(car); assertEquals(1, constraintViolations.size()); assertEquals("must be greater than or equal to 2", constraintViolations.iterator().next().getMessage()); Test public void carIsValid() Car car = new Car("Morris", "DD-AB-123", 2); SetConstraintViolationCar constraintViolations = validator.validate(car); assertEquals(0, constraintViolations.size()); In the setUp() method we get a Validator instance from the ValidatorFactory . A Validator instance is thread-safe and may be reused multiple times. For this reason we store it as field of our test class. We can use the Validator now to validate the different car instances in the test methods. 4Where to go next? The validate() method returns a set of ConstraintViolation instances, which we can iterate in order to see which validation errors occurred. The first three test methods show some expected constraint violations: • The NotNull constraint on manufacturer is violated in manufacturerIsNull() • The Size constraint on licensePlate is violated in licensePlateTooShort() • The Min constraint on seatCount is violated in seatCountTooLow() If the object validates successfully, validate() returns an empty set. Note that we only use classes from the package javax.validation from the Bean Validation API. As we don't reference any classes of the RI directly, it would be no problem to switch to another implementation of the API, should that need arise. 1.4. Where to go next? That concludes our 5 minute tour through the world of Hibernate Validator. Continue exploring the code examples or look at further examples referenced in Chapter 10, Further reading. To deepen your understanding of Hibernate Validator just continue reading Chapter 2, Validation step by step. In case your application has specific validation requirements have a look at Chapter 3, Creating custom constraints. 56Chapter 2. Validation step by step In this chapter we will see in more detail how to use Hibernate Validator to validate constraints for a given entity model. We will also learn which default constraints the Bean Validation specification provides and which additional constraints are only provided by Hibernate Validator. Let's start with how to add constraints to an entity. 2.1. Defining constraints Constraints in Bean Validation are expressed via Java annotations. In this section we show how to annotate an object model with these annotations. We have to differentiate between three different type of constraint annotations - field-, property-, and class-level annotations. Note Not all constraints can be placed on all of these levels. In fact, none of the default constraints defined by Bean Validation can be placed at class level. The java.lang.annotation.Target annotation in the constraint annotation itself determines on which elements a constraint can be placed. See Chapter 3, Creating custom constraints for more information. 2.1.1. Field-level constraints Constraints can be expressed by annotating a field of a class. Example 2.1, “Field level constraint” shows a field level configuration example: Example 2.1. Field level constraint package com.mycompany; import javax.validation.constraints.NotNull; public class Car NotNull private String manufacturer; AssertTrue private boolean isRegistered; public Car(String manufacturer, boolean isRegistered) super(); this.manufacturer = manufacturer; this.isRegistered = isRegistered; 7Chapter 2. Validation step by... When using field level constraints field access strategy is used to access the value to be validated. This means the bean validation provider directly accesses the instance variable and does not invoke the property accessor method also if such a method exists. Note The access type (private, protected or public) does not matter. Note Static fields and properties cannot be validated. Tip When validating byte code enhanced objects property level constraints should be used, because the byte code enhancing library won't be able to determine a field access via reflection. 2.1.2. Property-level constraints If your model class adheres to the JavaBeans http://java.sun.com/javase/technologies/desktop/ javabeans/index.jsp standard, it is also possible to annotate the properties of a bean class instead of its fields. Example 2.2, “Property level constraint” uses the same entity as in Example 2.1, “Field level constraint”, however, property level constraints are used. Note The property's getter method has to be annotated, not its setter. Example 2.2. Property level constraint package com.mycompany; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.NotNull; public class Car private String manufacturer; private boolean isRegistered; 8Class-level constraints public Car(String manufacturer, boolean isRegistered) super(); this.manufacturer = manufacturer; this.isRegistered = isRegistered; NotNull public String getManufacturer() return manufacturer; public void setManufacturer(String manufacturer) this.manufacturer = manufacturer; AssertTrue public boolean isRegistered() return isRegistered; public void setRegistered(boolean isRegistered) this.isRegistered = isRegistered; When using property level constraints property access strategy is used to access the value to be validated. This means the bean validation provider accesses the state via the property accessor method. One advantage of annotating properties instead of fields is that the constraints become part of the constrained type's API that way and users are aware of the existing constraints without having to examine the type's implementation. Tip It is recommended to stick either to field or property annotations within one class. It is not recommended to annotate a field and the accompanying getter method as this would cause the field to be validated twice. 2.1.3. Class-level constraints Last but not least, a constraint can also be placed on class level. When a constraint annotation is placed on this level the class instance itself passed to the ConstraintValidator. Class level constraints are useful if it is necessary to inspect more than a single property of the class to validate it or if a correlation between different state variables has to be evaluated. In Example 2.3, “Class level constraint” we add the property passengers to the class Car. We also add the constraint PassengerCount on the class level. We will later see how we can actually create this custom constraint (see Chapter 3, Creating custom constraints). For now it is enough to know that PassengerCount will ensure that there cannot be more passengers in a car than there are seats. 9Chapter 2. Validation step by... Example 2.3. Class level constraint package com.mycompany; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; PassengerCount public class Car NotNull private String manufacturer; NotNull Size(min = 2, max = 14) private String licensePlate; Min(2) private int seatCount; private ListPerson passengers; public Car(String manufacturer, String licencePlate, int seatCount) this.manufacturer = manufacturer; this.licensePlate = licencePlate; this.seatCount = seatCount; //getters and setters ... 2.1.4. Constraint inheritance When validating an object that implements an interface or extends another class, all constraint annotations on the implemented interface and parent class apply in the same manner as the constraints specified on the validated object itself. To make things clearer let's have a look at the following example: Example 2.4. Constraint inheritance using RentalCar package com.mycompany; import javax.validation.constraints.NotNull; public class RentalCar extends Car private String rentalStation; public RentalCar(String manufacturer, String rentalStation) super(manufacturer); this.rentalStation = rentalStation; 10Object graphs NotNull public String getRentalStation() return rentalStation; public void setRentalStation(String rentalStation) this.rentalStation = rentalStation; Our well-known class Car is now extended by RentalCar with the additional property rentalStation. If an instance of RentalCar is validated, not only the NotNull constraint on rentalStation is validated, but also the constraint on manufacturer from the parent class. The same would hold true, if Car were an interface implemented by RentalCar. Constraint annotations are aggregated if methods are overridden. If RentalCar would override the getManufacturer() method from Car any constraints annotated at the overriding method would be evaluated in addition to the NotNull constraint from the super-class. 2.1.5. Object graphs The Bean Validation API does not only allow to validate single class instances but also complete object graphs. To do so, just annotate a field or property representing a reference to another object with Valid. If the parent object is validated, all referenced objects annotated with Valid will be validated as well (as will be their children etc.). See Example 2.6, “Adding a driver to the car”. Example 2.5. Class Person package com.mycompany; import javax.validation.constraints.NotNull; public class Person NotNull private String name; public Person(String name) super(); this.name = name; public String getName() return name; public void setName(String name) this.name = name; 11Chapter 2. Validation step by... Example 2.6. Adding a driver to the car package com.mycompany; import javax.validation.Valid; import javax.validation.constraints.NotNull; public class Car NotNull Valid private Person driver; public Car(Person driver) this.driver = driver; //getters and setters ... If an instance of Car is validated, the referenced Person object will be validated as well, as the driver field is annotated with Valid. Therefore the validation of a Car will fail if the name field of the referenced Person instance is null. Object graph validation also works for collection-typed fields. That means any attributes that • are arrays • implement java.lang.Iterable (especially Collection, List and Set) • implement java.util.Map can be annotated with Valid, which will cause each contained element to be validated, when the parent object is validated. Example 2.7. Car with a list of passengers package com.mycompany; import java.util.ArrayList; import java.util.List; import javax.validation.Valid; import javax.validation.constraints.NotNull; public class Car NotNull Valid private ListPerson passengers = new ArrayListPerson(); public Car(ListPerson passengers) 12Validating constraints this.passengers = passengers; //getters and setters ... If a Car instance is validated, a ConstraintValidation will be created, if any of the Person objects contained in the passengers list has a null name. Note null values are getting ignored when validating object graphs. 2.2. Validating constraints The Validator interface is the main entry point to Bean Validation. In Section 5.1, “Configuration and ValidatorFactory” we will first show how to obtain an Validator instance. Afterwards we will learn how to use the different methods of the Validator interface. 2.2.1. Obtaining a Validator instance The first step towards validating an entity instance is to get hold of a Validator instance. The road to this instance leads via the Validation class and a ValidatorFactory . The easiest way is to use the static Validation.buildDefaultValidatorFactory() method: Example 2.8. Validation.buildDefaultValidatorFactory() ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); For other ways of obtaining a Validator instance see Chapter 5, Bootstrapping. For now we just want to see how we can use the Validator instance to validate entity instances. 2.2.2. Validator methods The Validator interface contains three methods that can be used to either validate entire entities or just a single properties of the entity. All three methods return a SetConstraintViolation. The set is empty, if the validation succeeds. Otherwise a ConstraintViolation instance is added for each violated constraint. All the validation methods have a var-args parameter which can be used to specify, which validation groups shall be considered when performing the validation. If the parameter is not specified the default validation group (javax.validation.groups.Default) will be used. We will go into more detail on the topic of validation groups in Section 2.3, “Validating groups” 13Chapter 2. Validation step by... 2.2.2.1. validate Use the validate() method to perform validation of all constraints of a given entity instance (see Example 2.9, “Usage of Validator.validate()” ). Example 2.9. Usage of Validator.validate() ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Car car = new Car(null); SetConstraintViolationCar constraintViolations = validator.validate(car); assertEquals(1, constraintViolations.size()); assertEquals("may not be null", constraintViolations.iterator().next().getMessage()); 2.2.2.2. validateProperty With help of the validateProperty() a single named property of a given object can be validated. The property name is the JavaBeans property name. Example 2.10. Usage of Validator.validateProperty() Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Car car = new Car(null); SetConstraintViolationCar constraintViolations = validator.validateProperty(car, "manufacturer"); assertEquals(1, constraintViolations.size()); assertEquals("may not be null", constraintViolations.iterator().next().getMessage()); Validator.validateProperty is for example used in the integration of Bean Validation into JSF 2 (see Section 7.4, “Presentation layer validation”). 2.2.2.3. validateValue Using the validateValue() method you can check, whether a single property of a given class can be validated successfully, if the property had the specified value: Example 2.11. Usage of Validator.validateValue() Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); SetConstraintViolationCar constraintViolations = validator.validateValue(Car.class, "manufacturer", null); assertEquals(1, constraintViolations.size()); 14

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.