In this example, we will see very basic validation @NotNull.
Step 1:
Step 3
CREATE TABLE `validatorexample1` (
`ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
`FirstName` VARCHAR(255) DEFAULT NULL,
`LastName` VARCHAR(255) DEFAULT NULL,
`MiddleName` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1
Now let us create the java bean for the above table.
Now let us add our test class.
Now right click test.java and select run as Java Application. You can see the following output and shows the validation constraints default message.
That’s all.
Project Structure
Environment
- Eclipse 3.7 Indigo IDE
- Hibernate 4.1.1
- JavaSE 1.6
- 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
- Right click on Project and Select Properties.
- Select Java Build Path.
- Click “Add External JARs..” and include the following jar 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 `validatorexample1` (`ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
`FirstName` VARCHAR(255) DEFAULT NULL,
`LastName` VARCHAR(255) DEFAULT NULL,
`MiddleName` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1
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;
@Entity
@Table(name = "validatorexample1")
public class validatorexample1 {
@Id
@GeneratedValue
@Column(name = "ID")
private int ID;
@Column(name = "FirstName")
@NotNull private String firstName;
@Column(name = "LastName")
@NotNull
private String lastName;
@Column(name = "middleName")
private String middleName;
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 String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
}
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.validatorexample1" />
</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>
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; @Entity @Table(name = "validatorexample1") public class validatorexample1 { @Id @GeneratedValue @Column(name = "ID") private int ID; @Column(name = "FirstName") @NotNull private String firstName; @Column(name = "LastName") @NotNull private String lastName; @Column(name = "middleName") private String middleName; 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 String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } }
<?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.validatorexample1" /> </session-factory> </hibernate-configuration>
Now let us add our test class.
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 domain.*; import HibernateUtilities.*; public class Test { public static void main(String[] args) { validatorexample1 v1 = new validatorexample1(); v1.setFirstName("John"); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<validatorexample1>> constraintViolations = validator .validate(v1); // printing the results for (ConstraintViolation<validatorexample1> constraintViolation : constraintViolations) { System.out.println(constraintViolation.getPropertyPath() + " -> " + constraintViolation.getMessage()); } Session session = HibernateUtil.beginTransaction(); session.save(v1); HibernateUtil.CommitTransaction(); } }
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. lastName -> may not be nulllog4j:WARN No appenders could be found for logger (org.jboss.logging). log4j:WARN Please initialize the log4j system properly. Hibernate: insert into validatorexample1 (FirstName, LastName, middleName) values (?, ?, ?)
That’s all.
Project Structure