Java Reference
In-Depth Information
private String state;
private String zip;
// Getters & setters go here
}
If you look at the Customer class in Listing 8-2, you can quickly determine some basic validation
rules.
Not null: firstName, lastName, address, city, state, zip.
Alphabetic: firstName, middleInitial, lastName, city, state.
Numeric: zip.
Size: middleInitial should be no longer than one character; state should be no
longer than two characters; and zip should be no longer than five characters.
There are further validations you can perform on the data provided zip is a valid ZIP code for the
city and state. However, this provides you with a good start. Now that you have identified the things you
want to validate, you can describe them to your validator via annotations on the Customer object.
Specifically, you will be using the @NotNull , @Size, and @Pattern annotations for these rules. To use
these, you will need to update your pom to reference a new library. You will use the Hibernate
implementation of the JSR 303 annotations, so you will need to add it to your project. Listing 8-3 shows
the dependency you need to add.
Listing 8-3. Hibernate Implementation of JSR 303 Dependency
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.2.GA</version>
</dependency>
With the dependency in place, you can actually update your code to use the annotations. Listing 8-4
shows their use on the Customer object.
Listing 8-4. Customer Object with Validation Annotations
package com.apress.springbatch.chapter8;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class Customer {
@NotNull
@Pattern(regexp="[a-zA-Z]+")
private String firstName;
@Size(min=1, max=1)
 
Search WWH ::




Custom Search