Validating Domain Objects in Hibernate Part 3: Creating Your Own Validator

Posted on September 27, 2007 by Scott Leberknight

This is the third in a series of short blogs describing how the Hibernate Validator allows you to define validation rules directly on domain objects where it belongs. In the second article I showed how to configure the Hibernate Validator and showed event-based and manual validation of domain objects. Here I'll show you how to create your own validators.

The most common use case is validation of individual properties on your domain objects. For example, is a property required; does it need to match a specific pattern; must it have a minimum and maximum length; or must it be a valid credit card number? Hibernate Validator makes creating validators for specific properties easy. In addition to property-specific validators, you can also write class-level validators. For example, maybe you allow certain fields to be blank, but if one of them is entered, then several others are required as well. You annotate property-level validators on properties (i.e. getter methods) and class-level validators on your domain object itself. Here's a short example showing both types of validator:

@Entity
@UserNameConfirmation
public class User extends BaseEntity {
    
    // id, version, etc. are defined in BaseEntity
    private String userName;
    private String firstName;
    private String lastName;
    private String ssn;
    
    @Required
    @Email
    public String getUserName() { return userName; }
    public void setUserName(String userName) { this.userName = userName; }
    
    @Email
    @Transient
    public String getUserNameConfirmation() { return userNameConfirmation; }
    public void setUserNameConfirmation(String userNameConfirmation) { this.userNameConfirmation = userNameConfirmation; }
    
    @Required
    @Length(min = 2, max = 50)
    public String getFirstName () { return firstName; }
    public void setFirstName() { this.firstName = firstName; }

    @Required
    @Length(min = 2, max = 50)
    public String getLastName () { return lastName; }
    public void setLastName() { this.lastName = lastName; }
    
    @Pattern(regex = "[0-9]{3}-[0-9]{2}-[0-9]{4}")
    public String getSsn() { return ssn; }
    public void setSsn(String ssn) { this.ssn = ssn; }
}

In the above example, there is a UserNameConfirmation annotation at the class level. This applies a validator that ensures a user name and a confirmation user name match, but only if the confirmation user name is supplied. There are also several property-level validators being applied: Email, Required, Length, and Pattern. I've also marked the userNameConfirmation property as transient with the @Transient annotation, since this is not actually a persistent property and we want Hibernate to ignore it during persistence operations; it is used only for validation purposes.

So let's actually create a validator now. The @Required validator I've been using in the example code is not one of the Hibernate validators that come out of the box. It has several other ones that are similar (@NotNull and @NotEmpty) but that I don't use in practice - more on why not in the next article though. To create a validator, you only need to do two things:

  1. Define a validation annotation
  2. Implement the validator class

Without further ado, here is the @Required annotation definition:

package com.nearinfinity.hibernate.validator;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import org.hibernate.validator.ValidatorClass;

/**
 * Designates a property that is required to have a value. It cannot be null or empty. The default message is
 * "validator.required" which is assumed to exist in the expected resource bundle
 * ValidatorMessages.properties.
 */
@Documented
@ValidatorClass(RequiredValidator.class)
@Target( { METHOD, FIELD })
@Retention(RUNTIME)
public @interface Required {

    String message() default "{validator.required}";

}

The important things in this code are:

  1. You specify the validator class (the class that performs the actual validation logic) using the ValidatorClass annotation, supplying the validator class implementation as the sole argument.
  2. You need to tell Java where the annotation is permitted via the Target annotation. We'll allow the @Required annotation on methods and fields.
  3. You need to tell Java to retain this annotation at runtime via the @Retention annotation, since Hibernate uses reflection to determine the validators for domain objects.
  4. You specify a message parameter with a default value with value "validator.required" and which is internationalized in the ValidatorMessages.properties resource bundle.

If there are additional parameters you need for your own validator, you can specify them in your annotation. For example, the Hibernate @Length validation annotation specifies a min and a max, like this:

@Documented
@ValidatorClass(LengthValidator.class)
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Length {
    int max() default Integer.MAX_VALUE;

    int min() default 0;

    String message() default "{validator.length}";
}

Now that we've defined the @Required validator annotation, we implement the actual validator class:

public class RequiredValidator implements Validator<Required>, Serializable {

    public void initialize(Required parameters) {
        // nothing to initialize
    }

    /**  @return true if the value is not null or an empty String */
    public boolean isValid(Object value) {
        if (value == null) {
            return false;
        }
        if (value instanceof String) {
            String stringValue = (String) value;
            if (stringValue.trim().length() == 0) {
                return false;
            }
        }
        return true;
    }
}

The important points in the validator implementation class are:

  1. The validator must implement the Hibernate Validator interface, which is parametrized by the validator annotation.
  2. You should also implement Serializable.

The Validator interface is very simple consisting of only two methods: initialize and isValid. The initialize method allows custom initialization, for example you can initialize parameters defined in your validation annotation such as the "min" and "max" in the Hibernate @Length annotation. The isValid method does the real work and validates the object supplied as an argument. That's pretty much it. Implementing class-level validators like the @UserNameConfirmation annotation I showed in an earlier example works exactly the same way. About the only difference is that you probably will restrict the annotation to types, i.e. classes using @Target({ TYPE }). Now, all that's left is to annotate your domain objects!

In the next article I'll explain my earlier statement that I don't use the @NotNull or @NotEmpty annotations in my domain objects.

Validating Domain Objects in Hibernate Part 2: Enabling Validation

Posted on September 17, 2007 by Scott Leberknight

This is the second in a series of short blogs describing how the Hibernate Validator allows you to define validation rules directly on domain objects where it belongs. In the first article I introduced the Hibernate Validator and showed a simple example of annotating a domain object. In this article I'll show you how to enable event-based validation, meaning when an event like a save or update occurs, Hibernate will automatically validate the objects being saved and throw an exception if any of them are invalid. I'll also show how you can manually validate objects using the validator API.

Prior to Hibernate Core version 3.2.4 (or around thereabouts) enabling event-based validation required explicit configuration. In plain Hibernate (i.e. standalone) you configure event-based validation like this:

<!-- Plain Hibernate Configuration File (e.g. hibernate.cfg.xml) -->
<hibernate-configuration>
  <session-factory>
    <!-- other configuration -->
    <event type="pre-update">
      <listener class="org.hibernate.validator.event.ValidateEventListener"/>
    </event>
    <event type="pre-insert">
      <listener class="org.hibernate.validator.event.ValidateEventListener"/>
    </event>
  </session-factory>
</hibernate-configuration>

Since many people use Hibernate in a Spring environment, you would add the following to the AnnotationSessionFactoryBean in your Spring application context file:

<!-- Spring-based configuration (e.g. applicationContext-hibernate.xml) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <!-- other configuration -->
  <property name="eventListeners">
    <map>
      <entry key="pre-update">
        <bean class="org.hibernate.validator.event.ValidateEventListener"/>
      </entry>
      <entry key="pre-insert">
        <bean class="org.hibernate.validator.event.ValidateEventListener"/>
      </entry>
    </map>
  </property>
</bean>

So basically all you are doing is configuring the ValidateEventListener event listener class to fire on "pre-update" and "pre-insert" events. So at runtime Hibernate will validate annotated domain objects before inserting or updating anything in the database. There is nothing particularly special here. Hibernate provides a ton of hook points into the various Hibernate events such as save, update, delete, persist, etc. via a listener model, and the Hibernate Validator simply hooks into this mechanism. Note that you need the Hibernate Validator JAR file in your CLASSPATH as it is not part of the core distribution.

As of Hibernate Core 3.2.4 (or somewhere around that version since I can't seem to find it in the release notes anywhere), Hibernate tries to help you out by auto-registering the ValidateEventListener if it is present in the CLASSPATH. Take a look at the following code snippet from the Hibernate AnnotationConfiguration class' buildSessionFactory() method:

// From org.hibernate.cfg.AnnotationConfiguration
public SessionFactory buildSessionFactory() throws HibernateException {
    // ...
    // ...add validator events if the jar is available...
    boolean enableValidatorListeners = ! 
        "false".equalsIgnoreCase( getProperty( "hibernate.validator.autoregister_listeners" ) );
    Class validateEventListenerClass = null;
    try {
        validateEventListenerClass = ReflectHelper.classForName(
                "org.hibernate.validator.event.ValidateEventListener",
                AnnotationConfiguration.class );
    }
    catch (ClassNotFoundException e) {
        //validator is not present
        log.debug( "Validator not present in classpath, ignoring event listener registration" );
    }
    
    // ...now if enableValidatorListeners is true, register a ValidateEventListener...
    // ...for pre-insert and pre-update events automagically (trying to not register if already configured)...
    
    // ...rest of method... 
}

The salient points of the above code are:

  1. Automatic registration occurs unless the hibernate.validator.autoregister_listeners property is "false."
  2. Hibernate uses reflection to determine if the ValidateEventListener class is available in the CLASSPATH.
  3. Hibernate does not register ValidateEventListener if it is already registered, e.g. via explicit configuration.

Regardless of how the configuratio has occurred, once configured everything works exactly the same. So now if you had code that saved a domain object you could catch an InvalidStateException in your code, which is the type of exception Hibernate Validator throws when validation fails. For example, you could write:

List<String> allErrors = new ArrayList<String>();
try {
    session.save(user);
}
catch (InvalidStateException ex) {
    for (InvalidValue error : ex.getInvalidValues()) {
        allErrors.add(humanize(error.getPropertyName()) + " " + error.getMessage());
    }
    // clean up...
}

That's pretty much it. You catch an InvalidStateException and from that exception you can get an array of InvalidValue objects. Each InvalidValue object contains the property name on which the validation error occurred, and a message such as "is required" or "is not a well-formed email address." The messages come from (by default) a standard Java resource bundle named ValidatorMessages.properties so the validation messages are fully internationalized depending on the locale. The property names will be the JavaBean property name, for example "firstName" so you probably need an extra translation step to convert the Java property notation to a human-readable one. In the example above I have a method named humanize that presumably translates "firstName" to "First Name" assuming a US locale.

Last, what if you want to manually validate an object? It is also very simple. The following code shows how to do it:

User user = getUserById(id);  // get object to validate somehow...

ClassValidator<User> validator = new ClassValidator<User>(User.class);
InvalidValue[] errors = validator.getInvalidValues(user);

Pretty simple. This allows you to validate domain objects before sending them to Hibernate to be persisted, which might be beneficial in certain cases. For example, you might want to perform validation in a service layer manually before sending objects to a data access tier which interacts with Hibernate. The one big difference is that event-based validation automatically validates parent and child objects (i.e. the object graph being saved) whereas the manual validation does not unless you annotate the child collection with @Valid.

In this article I've shown how to enable the Hibernate Validator and how to use event-based and manual validation of domain objects. In the next article I'll show you how to create your own validators in case you need more than the ones Hibernate Validator provides out of the box.

Validating Domain Objects in Hibernate Part 1: Introduction

Posted on September 10, 2007 by Scott Leberknight

This is the first in a series of short blogs showing how you can use Hibernate to validate your domain objects. Here I'll provide a brief introduction to validating your domain objects using Hibernate and why it matters. In future installments I'll show you how to enable the validations you apply to your domain objects, how to create your own custom validators, and provide some tips about integrating the Hibernate validator into your applications.

Every system needs data validation. In Java-based web applications using MVC frameworks like Struts, Spring MVC, or JSF, most developers simply use their framework's built-in validation scheme. Each of the aforementioned frameworks provides a way to validate form data, but this is usually restricted to the web tier. Struts provides ActionForms that have a validate() method you implement or you can use the Jakarta Commons Validator; JSF uses custom tags like <f:validateLength/> in the presentation tier; and Spring MVC has a Validator interface that can be easily plugged into Spring MVC's SimpleFormController. These solutions are either tied directly to the web tier or would require a bunch of infrastructure (or plumbing) code to make it work across all tiers seamlessly.

This is fine is many cases, but what happens when you expose functionality via a web service (I won't get into a REST vs WS-Death Star argument here, OK?) and you still need data validation? In fact usually you need the exact same validation for the domain objects. Now what? Many developers simply end up copy/pasting validation code. Ugh. Others come up with their own validation framework to keep things DRY but end up making things more complicated, plus they are writing infrastructure code instead of business logic. Along came Ruby on Rails which made it trivial to declare validation on domain objects and have that validation automatically apply no matter where the domain objects are used, i.e. in web controllers, web services, etc. This was probably most Java developers' first experience with applying validation directly to domain objects, and they were jealous (or at least I was).

Fortunately Hibernate provides the Hibernate Validator which allows you to annotate your domain objects with validation constraints. For example:

@Entity
public class User extends BaseEntity {
	
    // id, version, etc. are defined in BaseEntity
    private String userName;
    private String firstName;
    private String lastName;
    private String ssn;
	
    @Required
    @Email
    public String getUserName() { return userName; }
    public void setUserName(String userName) { this.userName = userName; }
	
    @Required
    @Length(min = 2, max = 50)
    public String getFirstName () { return firstName; }
    public void setFirstName() { this.firstName = firstName; }

    @Required
    @Length(min = 2, max = 50)
    public String getLastName () { return lastName; }
    public void setLastName() { this.lastName = lastName; }
	
    @Pattern(regex = "[0-9]{3}-[0-9]{2}-[0-9]{4}")
    public String getSsn() { return ssn; }
    public void setSsn(String ssn) { this.ssn = ssn; }
}

In the above code, we are mandating the following validation rules on all User objects:

  • User name is required and must be a well-formed email address.
  • First name is required and must be between 2 and 50 characters in length.
  • Last Name is required and must be between 2 and 50 characters in length.
  • Social Security Number is not required, but if present must match the format NNN-NN-NNNN.

With these annotations, we can now have any User object validated automatically and the same validation rules will apply no matter where the User object is used, i.e. the validation is where it should be, in the problem domain and not tied to the a specific application tier. In the next article, I'll show how to actually enable the Hibernate Validator and how to validate objects.