Hibernate Validator - Creating custom constraints–Example

In this post, we will see how we can create our own custom constraints tailored to our specific requirements.

Creating our own custom constraint is not that much complicated, it is a matter of defining two steps :
a) Create a constraint annotation
b) Create a constraint validation

I am going to explain step by step for creating our own constraint by taking hibernate documentation example as here..
Now let us start.

Environment


  1. Eclipse 3.7 Indigo IDE
  2. Hibernate 4.1.1
  3. JavaSE 1.6
  4. MySQL 5.1

Step 1:
Let us set up the environment first. Follow this post to set up Hibernate with java in eclipse IDE.

Step 2:
We need to add some more jar files for Validator. Please follow the steps

  1. Right click on Project and Select Properties.
  2. Select Java Build Path.
  3. Click “Add External JARs..” and include the following jar files. (you can also download by clicking the following files)

hibernate-validator-4.0.2.GA.jar
hibernate-validator-annotation-processor-4.1.0.Final.jar
slf4j-simple-1.4.2.jar
log4j-1.2.15.jar
slf4j-api-1.4.2.jar
validation-api-1.0.0.GA.jar

Step 3
In the mysql, create the following table.


CREATE TABLE `validatorexample4` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `firstName` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1

Step 4
Now let us create the java bean without our constraint. Later we will come back , add our newly created custom constraint.

 

package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "validatorexample4")
public class validatorexample4 {

@Id
@GeneratedValue
@Column(name = "ID")
private int ID;

@Column(name = "FirstName")
private String firstName;

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

}




Now let us map this class in the hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Mapping Classes -->
<mapping class="domain.validatorexample4" />

</session-factory>
</hibernate-configuration>

Very Important, We need add one more property in the above xml file as follows
<property name="javax.persistence.validation.mode">none</property>




 

Now let us create our constraint annotation as follows.


First we need a way to express the two case modes. We might use String constants, but a better way to go is to use a Java 5 enum for that purpose:

package myConstraints;

public enum CaseMode {
UPPER, LOWER;
}


Now we can define the actual constraint annotation. If you've never designed an annotation before, this may look a bit scary, but actually it's not that hard: It is a matter of writing some boiler plate code and filling in the blanks.




package myConstraints;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

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

import javax.validation.Constraint;
import javax.validation.Payload;

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckCaseValidator.class)
@Documented
public @interface CheckCase {

String message() default "{default message}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

CaseMode value();

}




  • The annotation interface has three mandatory attributes: message, groups and payload

  • @Target({ METHOD, FIELD, ANNOTATION_TYPE }): Says, that methods, fields and annotation declarations may be annotated with @CheckCase (but not type declarations e.g.)

  • @Retention(RUNTIME): Specifies, that annotations of this type will be available at runtime by the means of reflection

  • @Constraint(validatedBy = CheckCaseValidator.class): Specifies the validator to be used to validate elements annotated with @CheckCase

  • @Documented: Says, that the use of @CheckCase will be contained in the JavaDoc of elements annotated with i

Next, we need to implement a constraint validator, that's able to validate elements with a @CheckCaseannotation. To do so, we implement the interface ConstraintValidator as shown below:



package myConstraints;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {

private CaseMode caseMode;

public void initialize(CheckCase constraintAnnotation) {
this.caseMode = constraintAnnotation.value();
}

public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

if (object == null)
return true;

boolean isValid;
if (caseMode == CaseMode.UPPER) {
isValid = object.equals(object.toUpperCase());
}
else {
isValid = object.equals(object.toLowerCase());
}

return isValid;
}

}


The ConstraintValidator interface defines two type parameters, which we set in our implementation. The first one specifies the annotation type to be validated (in our example CheckCase), the second one the type of elements, which the validator can handle (here String).


In case a constraint annotation is allowed at elements of different types, a ConstraintValidator for each allowed type has to be implemented and registered at the constraint annotation as shown above.


The implementation of the validator is straightforward. The initialize() method gives us access to the attribute values of the annotation to be validated. In the example we store the CaseMode in a field of the validator for further usage.


In the isValid() method we implement the logic, that determines, whether a String is valid according to a given @CheckCase annotation or not. This decision depends on the case mode retrieved in initialize(). As the Bean Validation specification recommends, we consider null values as being valid. If null is not a valid value for an element, it should be annotated with @NotNull explicitly.




Now, let us go back to bean and add our custom constraint as follows.

package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import myConstraints.CaseMode;
import myConstraints.CheckCase;

@Entity
@Table(name = "validatorexample4")
public class validatorexample4 {

@Id
@GeneratedValue
@Column(name = "ID")
private int ID;

@Column(name = "FirstName")
@CheckCase(value = CaseMode.UPPER, message="First Name should be in upper case")
private String firstName;

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

}

Now, in order to test our code, we will create our test class as follows

package test;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.Session;
import HibernateUtilities.HibernateUtil;
import domain.validatorexample4;

public class Test {
public static void main(String[] args) {


validatorexample4 v1 = new validatorexample4();
v1.setFirstName("a");

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<validatorexample4>> constraintViolations = validator
.validate(v1);

// printing the results
for (ConstraintViolation<validatorexample4> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getPropertyPath() + " -> "
+ constraintViolation.getMessage());
}
Session session = HibernateUtil.beginTransaction();
session.save(v1);
HibernateUtil.CommitTransaction();

}
}

Now right click test.java and select run as Java Application. You can see the following output and shows the validation constraints.

2 [main] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.0.2.GA
13 [main] INFO org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
firstName -> First Name should be in upper case
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into validatorexample4 (FirstName) values (?)










That’s all


Project Structure:
image