Welcome to Hibernate Validator Annotations Example tutorial. Today, i will show you Hibernate Validator API with a full working example. Hibernate Validator is a JSR 303 implementation for bean validation. The way to work with hibernate framework is to define constraints for java bean fields, and then, validating the bean.
- Defining validation data using annotation and/or XML.
- Full object validation, including inner objects using recursion
- Create customized constraints and validators.
- Customized error messages.
- Define groups(profiles).
- Create a Traversable Resolver.
Other interesting posts you may like
Create project directory structure
In this Hibernate Validator Annotations Example, we will create java project with final directory structure:
Maven dependencies
We provide the required Hibernate and MySQL dependency in pom.xml like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode.hibernate</groupId> <artifactId>HibernateValidatorAnnotationsExample</artifactId> <version>0.0.1-SNAPSHOT</version> <description>Hibernate validator annotations example</description> <dependencies> <!-- Hibernate Core API --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.11.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.5.6-Final</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.1.Final</version> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.4</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</version> </dependency> </dependencies> </project> |
Let’s look into the above dependencies:
We need to add JSR303 and Hibernate Validator dependencies in pom.xml to use them.
1 2 3 4 5 6 7 8 9 10 |
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.1.Final</version> </dependency> |
However, Hibernate Validator requires Expression Language API dependencies (JSR 341) for evaluating dynamic expressions in constraint violation messages. Required dependencies are
1 2 3 4 5 6 7 8 9 10 |
<dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.4</version> </dependency> |
If you run the application on server application such as JBoss, you can skip over this dependencies because it’s already provided.
Create bean validation
Create a Student class and add some validation constraints to it. You also refer to other validation constraints
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
package com.javabycode.hibernate.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; @Entity @Table(name = "STUDENT") public class Student implements Serializable { private static final long serialVersionUID = 6832006422622219737L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotEmpty(message="Name cannot be empty") @Size(min=5, max=30) @Column(name = "NAME", nullable = false) private String name; @NotNull @Past @Column(name = "ENTERING_DATE", nullable = false) private Date enteringDate; @NotEmpty @Column(name = "NATIONALITY", nullable = false) private String nationality; @NotNull(message="Code cannot be null") @Size(min=5, max=5) @Column(name = "CODE", nullable = false) private String code; public Student(){ } public Student(String name, Date enteringDate,String nationality, String code){ this.name = name; this.enteringDate = enteringDate; this.nationality = nationality; this.code = code; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setCode(String code) { this.code = code; } public void setEnteringDate(Date enteringDate) { this.enteringDate = enteringDate; } public void setNationality(String nationality) { this.nationality = nationality; } public String getCode() { return code; } public Date getEnteringDate() { return enteringDate; } public String getNationality() { return nationality; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + name.hashCode(); result = prime * result + ((code == null) ? 0 : code.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Student)) return false; Student other = (Student) obj; if (id != other.id) return false; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; return true; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", enteringDate=" + enteringDate + ", nationality=" + nationality + ", code=" + code + "]"; } } |
As you see above, we can also provide custom error message for any validation. If not the hibernate built-in error message will be used.
Hibernate Validator Custom Error Messages
We can create our custom error messages too, all we need is to push ValidationMessages.properties file into the classpath.
ValidationMessages.properties
1 2 |
javax.validation.constraints.NotNull.message = attribute is required org.hibernate.validator.constraints.NotEmpty.message = attribute is required |
Hibernate validator also support localization, in that case the file names follow the pattern of bundle name with language code and country code, for example ValidationMessages_en_US.properties
The property name for message is fully classified annotation name with message at the end, you can easily figure out from above examples.
Create a test program
In this Hibernate Validator Annotations Example tutorial, we create a main class in which we save a student object missed some fields. Then we validate that object by using Hibernate validator API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.javabycode.hibernate; import java.util.Set; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import javax.validation.ConstraintViolation; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.javabycode.hibernate.model.Student; public class HibernateValidatorAnnotationsExample { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Student student = new Student("", null, "", "1234569"); Set<ConstraintViolation<Student>> constraintViolations = validator.validate(student); // printing the validation errors for (ConstraintViolation<Student> constraintViolation : constraintViolations) { System.out.println(constraintViolation.getPropertyPath() + " -> " + constraintViolation.getMessage()); } Session session = sessionFactory.openSession(); session.save(student); sessionFactory.close(); } } |
Run above main and produce the output like below
1 2 3 4 5 6 7 8 9 10 11 12 13 |
nationality -> attribute is required name -> Name cannot be empty code -> size must be between 5 and 5 name -> size must be between 5 and 30 enteringDate -> attribute is required Exception in thread "main" javax.validation.ConstraintViolationException: Validation failed for classes [com.javabycode.hibernate.model.Student] during persist time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='attribute is required', propertyPath=nationality, rootBeanClass=class com.javabycode.hibernate.model.Student, messageTemplate='{org.hibernate.validator.constraints.NotEmpty.message}'} ConstraintViolationImpl{interpolatedMessage='Name cannot be empty', propertyPath=name, rootBeanClass=class com.javabycode.hibernate.model.Student, messageTemplate='Name cannot be empty'} ConstraintViolationImpl{interpolatedMessage='size must be between 5 and 5', propertyPath=code, rootBeanClass=class com.javabycode.hibernate.model.Student, messageTemplate='{javax.validation.constraints.Size.message}'} ConstraintViolationImpl{interpolatedMessage='size must be between 5 and 30', propertyPath=name, rootBeanClass=class com.javabycode.hibernate.model.Student, messageTemplate='{javax.validation.constraints.Size.message}'} ConstraintViolationImpl{interpolatedMessage='attribute is required', propertyPath=enteringDate, rootBeanClass=class com.javabycode.hibernate.model.Student, messageTemplate='{javax.validation.constraints.NotNull.message}'} ] |
That’s it on the tutorial Hibernate Validator Annotations Example
Download complete source code, please click link below
HibernateValidatorAnnotationsExample.zip (322 downloads)