BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Java EE 6 Bean Validation Provides Entity Validation Metadata Model and API

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

This item in japanese

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
Style

BT