Wednesday, 29 August 2012

Hibernate Validator Example 2

In this example, we will see some more validation constraints such as @email, @past, @length, etc. And also we will also define custom error message.


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

Step 1:
Let us set the environment. 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.


Step 3
In the mysql, create the following table.

CREATE TABLE `validatorexample3` (
  `FirstName` VARCHAR(255) DEFAULT NULL,
  `CustomerNumber` VARCHAR(255) DEFAULT NULL,


Step 4

Now let us create the java bean for the above table.
package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

@Table(name = "validatorexample3")
public class validatorexample3 {

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

@NotNull(message="First name cannot be empty")
@Size(min = 2,message="First name is too small")
@Column(name = "FirstName")
private String firstName;

@Length(min = 2, max = 50, message="LastName should be 2 to 50 Characters size")
@Column(name = "LastName")
private String lastName;

@Column(name = "BirthDate")
@Past(message="Date of birth should be past date")
private Date birthDate;

@Pattern(regexp = "^[a-zA-Z]{2}-\\d+$", message="Invalid Customer Number")
@Column(name = "CustomerNumber")
private String customerNumber;

@Pattern(regexp= "[0-9]{3}-[0-9]{2}-[0-9]{4}", message="Invalid SSN format")
@Column(name = "ssn")
private String ssn;

@Column(name = "Email")
@org.hibernate.validator.constraints.Email(message="Invalid Email Format")
private String Email;

@Length(min = 5, max = 5, message = "{zip.length}")
@Pattern(regexp = "[0-9]+", message="Invalid Zip")
@Column(name = "zip")
private String zip;

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;

public String getLastName() {
return lastName;

public void setLastName(String lastName) {
this.lastName = lastName;

public Date getBirthDate() {
return birthDate;

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;

public String getCustomerNumber() {
return customerNumber;

public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;

public String getSsn() {
return ssn;

public void setSsn(String ssn) {
this.ssn = ssn;

public String getEmail() {
return Email;

public void setEmail(String email) {
Email = email;

public String getZip() {
return zip;

public void setZip(String zip) { = zip;


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"
<!-- 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.validatorexample3" />


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 add our test class.

package test;

import java.text.SimpleDateFormat;
import java.util.Date;
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.validatorexample3;

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

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

validatorexample3 v1 = new validatorexample3();
v1.setBirthDate(sdf.parse(sdf.format(new Date())+1));

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

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


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

2 [main] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.0.2.GA
12 [main] INFO org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
Email -> Invalid Email Format
lastName -> LastName should be 2 to 50 Characters size
birthDate -> Date of birth should be past date
zip -> {zip.length}
zip -> Invalid Zip
firstName -> First name is too small
ssn -> Invalid SSN format
customerNumber -> Invalid Customer Number

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into validatorexample3 (Email, BirthDate, CustomerNumber, FirstName, LastName, ssn, zip) values (?, ?, ?, ?, ?, ?, ?)

That’s all.

Project Structure


1 comment:

  1. We are a third party technical support service. Avast Customer Support is here to help you out with the whole procedure to Download Avast Antivirus online, We not only fix your Avast Support related issues but will guide with how to get started with your new Avast product once it gets installed successfully. Call on our Toll Free no. 1 855 966 3855
    Gmail Customer service is a third party technical support service for Gmail users when they face any technical issue or error in their Gmail account. Our Gmail Customer Support team solves issues like forgot Gmail account password, Gmail configuration or Sync issues, recover deleted emails and many more. Toll Free number (800) 986-9271
    How you install or reinstall Office 365 or Office 2016 depends on whether your Office product is part of an Office for home or Office for business plan. If you're not sure what you have, see what office com setup products are included in each plan and then follow the steps for your product. The steps below also apply if you're installing a single, stand-alone Office application such as Access 2016 or Visio 2016. Need Help with office setup Enter Product Key? Call 1-800-000-0000 Toll Free
    Norton Tech Support is a third party service provider and not in any way associated with Norton or any of its partner companies. We offer support for Norton products and sell subscription based additional warranty on computer and other peripheral devices. Call our Toll Free number 1 855 966 3855
    Other Services
    Norton Toll Free , Office-Setup ,