BT

Java EE 6 Bean Validation Provides Entity Validation Metadata Model and API

| by Srini Penchikala Follow 40 Followers on Mar 02, 2010. Estimated reading time: 4 minutes |

So far in the Java Enterprise Edition (JEE) Version 6 series, we've looked at the Java API for RESTful Web Services (JAX-RS), Contexts and Dependency Injection (CDI), the Web Tier (Servlet 3, JSF 2), and EJB 3.1. In this concluding part we look at Bean Validation (JSR 303), one of the core features of JavaEE 6 release. It defines a metadata model and an API for entity validation. The default metadata source for validations is annotations, but the developers can extend the meta-data through the use of XML descriptors. The Validation API is not tied to a specific application tier or programming model so the same set of validations can be shared by all the layers of an application. It also provides a mechanism to add custom validation constraints by extending the Validation API as well as a way to query the constraint metadata repository.

Prior to Bean Validation feature in JEE6, developers had to write their validation rules in the presentation framework, then in the business layer, and also in the persistent layer and keep all of them synchronized which is time consuming and error-prone. The bean validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component such as a backing bean. Constraints can be built-in annotations (available in the javax.validation.constraints package) or they can be user-defined. Some of the commonly used built-in annotations are listed below:

  • Min: The annotated element, marked with @Min, must be a number whose value must be higher or equal to the specified minimum.
  • Max: The @Max annotation verifies that the annotated element is a number whose value must be lower or equal to the specified maximum.
  • Size: The @Size validates that the annotated element must be between specified minimum and maximum boundaries. The supported types for the size validation are String, Collection (collection size is evaluated), Map, and Array.
  • NotNull: @NotNull annotation ensures that the annotated element must not be null.
  • Null: The annotated element must be null when marked with @Null annotation.
  • Pattern: This annotation verifies that the annotated element (String) must match the specified Java regular expression.

Here is an example described in Java EE 6 article, that declares some constraints through Bean Validation annotations:

   public class Address {
       @NotNull @Size(max=30)
       private String addressline1;

       @Size(max=30)
       private String addressline2;

       public String getAddressline1() {
          return addressline1;
       }

       public void setAddressline1(String addressline1) {
          this.addressline1 = addressline1;
       }
   }

The @NotNull annotation specifies that the annotated element, addressline1, must not be null. The @Size annotation specifies that the annotated elements, addressline1 and addressline2, must not be longer than the specified maximum, 30 characters.

When an Address object is validated, the addressline1 value is passed to a validator class that is defined for the @NotNull constraint as well as to a validator class defined for the @Size constraint. The addressline2 value is also passed to the validator class for the @Size constraint. The pertinent validator classes perform the validations.

Below is an example of a custom constraint named ZipCode:

   @Size(min=5, max=5)
   @ConstraintValidator(ZipcodeValidator.class)
   @Documented
   @Target({ANNOTATION_TYPE, METHOD, FIELD})
   @Retention(RUNTIME)
   public @interface ZipCode {
       String message() default "Wrong zipcode";
       String[] groups() default {};
   }

You can specify the @ZipCode constraint on a class, field, or property just like any other constraint.

   public class Address {
       @ZipCode
       private String zipCode;

       public String getZipCode() {
          return zipCode;
       }

       public void setZipCode(String zipCode) {
          this.zipCode = zipCode;
       }
   }

Validation API:

Validation API describes how to programmatically validate a JavaBean. The default package for the Bean Validation API is javax.validation. Some of the classes in this API library are listed below:

ConstraintValidator: This is the interface implemented by a constraint validation implementation. It defines the logic to validate a given constraint for a given object type.

Validator: The Validator interface holds contracts to validate object graphs. The implementations of this interface must be thread-safe.

ConstraintViolation: The constraint failure on a given bean is described using ConstraintViolation interface which exposes the constraint violation context as well as the message describing the violation.

ValidationException: If some unrecoverable failure happens during validation, a ValidationException is raised. This exception can be specialized in some situations (invalid group definition, invalid constraint definition, invalid constraint declaration).

Constraint metadata request APIs:

The Bean Validation specification provides a way to query the constraint repository. This API is expected to be used for tooling support as well as integration with other frameworks, libraries and JSRs. The Bean Validation specification aims to provide both a validation engine and a metadata repository for object constraints. Frameworks (Java EE or Java SE) in need for constraint definition, validation and metadata will be able to rely on the Bean Validation specification for these services avoiding any unnecessary duplication work from an application and infrastructure point of view.

The Bean Validation is integrated with JSF 2.0 and JPA 2.0 versions. In JSF, you bind form inputs to properties of your domain model. JSF 2 and Bean Validation figure out which property you are binding to and execute the constraints associated to it to expose constraint violations to the user.

Hibernate Validator 4 is the reference implementation framework of Bean Validation specification. Hibernate Validator's latest version adds some new features like validation grouping, native integration with JPA2 and JSF2, and an extended annotation set.

Rate this Article

Adoption Stage
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

GraniteDS 2.2 Implementation of the Bean Validation Specification by Franck Wolff

Hi,

Just to let people know that GraniteDS 2.2 comes with an ActionScript3/Flex implementation of the JSR-303 specification. Furthermore, its code generation tools may be configured to automatically replicate Java bean constraint annotation into the generated AS3 model. Entity validation may therefore be performed in the Flex client application the same way it will be perform on server side before persistence.

See documentation here: www.graniteds.org/confluence/display/DOC22/3.+V....

FW.

Broken link to Hibernate Validator by Daniel Serodio

The link to the Hibernate Validator docs is broken, the new one is docs.jboss.org/hibernate/validator/4.3/referenc...

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

2 Discuss
BT