Validation Example in Hibernate

In this article, we will cover How to validate fields in Hibernate using Java bean Validator.

Validation is an important part of any web application. It helps us to create error-free code or applications. It is required from the security point of view.

  • Nowadays, we have a good amount of libraries available for Validation.
  • Whether it is client-side or Server-side each Framework is building itself to provide Validation Libraries to the developers.
  • We just need to add it and use it.

Hibernate Validator provides us with classes to validate Java beans. It has a good amount of annotation that we can apply to the property of the bean. Let’s see some of them with descriptions.

Annotation

Description

@Email It validates whether the character sequence is a valid email.
@Max It validates whether the value is less than or equal to the specified maximum.
@Min It validates whether the value is greater than or equal to the specified minimum.
@NotEmpty It validates whether the value is not null/not empty.
@Null It validates whether the value is null.
@NotNull It validates whether the value is not null.
@NotBlank It validates whether the value is not null and trimmed length > 0
@Digits It validates whether the value is a number.
@Pattern It validates whether the value matches with regex.
@Size It validates whether the value is between the min and max.
@Negative It validates whether the value is Negative
@NegativeorZero It is the same as @Neagtive but allows Zero value.
@Future It validates whether the date is of future
@FutureOrPresent It validates whether the date is in the present or in the future.
@PastOrPresent It validates whether the date is in the past or in the present.

Let’s see how we can implement it.

Create a Maven project and add the following dependencies in pom.xml

  • Add the Java bean Validation API.
  • Add the Hibernate Validator
  • Add the Hibernate validator annotation processor to verify validation annotations usage at compile time.
  • Add the javax-el-api and add the implementation java.ex

pom.xml

<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</groupId>
  <artifactId>Hibernate-Validation</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Hibernate-Validation</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- Java bean validation API - Spec -->
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>2.0.1.Final</version>
    </dependency>

    <!-- Hibernate validator - Bean validation API Implementation -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.0.11.Final</version>
    </dependency>

    <!-- Verify validation annotations usage at compile time -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator-annotation-processor</artifactId>
      <version>6.0.11.Final</version>
    </dependency>

    <!-- Unified Expression Language - Spec -->
    <dependency>
      <groupId>javax.el</groupId>
      <artifactId>javax.el-api</artifactId>
      <version>3.0.1-b06</version>
    </dependency>

    <!-- Unified Expression Language - Implementation -->
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>javax.el</artifactId>
      <version>2.2.6</version>
    </dependency>
  </dependencies>
</project>

Create a Bean Class with annotation.

package com.Hibernate_Validation;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Student {

  @NotNull(message = "Please Enter Id")
  private long id;
  
  @Size(max = 20, min = 5, message = "{student.name.invalid}")
  @NotEmpty(message = "Please enter name")
  private String name;
  
  @Email(message = "{student.email.invalid}")
  @NotEmpty(message = "Please enter email")
  private String email;

  public Student(@NotNull(message = "Please Enter Id") long id,
      @Size(max = 20, min = 5, message = "{student.name.invalid}") @NotEmpty(message = "Please enter name") String name,
      @Email(message = "{student.email.invalid}") @NotEmpty(message = "Please enter email") String email) {
    super();
    this.id = id;
    this.name = name;
    this.email = email;
  }

  
  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 String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }
  
  
}

Create a property file ValidationMessages.properties to store the message in Key value pair. (Just right-click on the project name and click New > Other > Search properties > Ok)

student.name.invalid=Invalid Name
student.email.invalid=Invalid Email Id.

Now, Test the Validation in Test.java

package com.Hibernate_Validation;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.hibernate.validator.ap.ConstraintValidationProcessor;

/**
 * Hello world!
 *
 */
public class Test 
{
    public static void main( String[] args )
    {
        ValidatorFactory validatorFactory =Validation.buildDefaultValidatorFactory();
        Validator validator =validatorFactory.getValidator();
        Student student = new Student(1, "N", "n");
        Set<ConstraintViolation<Student>> constraintViolations = validator.validate(student);
        if(constraintViolations.size()>0){
        	for(ConstraintViolation<Student> constraintViolation2 :  constraintViolations ){
        		System.out.println(constraintViolation2.getMessage());
        	}
        }else
        	{
        		System.out.println("Valid");
        	}
        }
        
    }
  • On line no: 20, Create a ValidatorFactory that will return the validator.
  • ¬†On line no: 21, It validates the instance of a bean.
  • On line no: 22, Student Bean Object is created and passed with invalid Name and invalid Email id and valid Id.
  • On line no: 23, ConstarintViolation Interface is used to describe constraint violation.
  • On line no: 24, We checked the constraint and display errors if any.

Output

May 04, 2021 10:19:59 AM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 6.0.11.Final
Invalid Name
Invalid Email Id.

Here, we can see the Message Invalid Name and Invalid Email from the property File. Thus, this is how we do validation in Hibernate using Java Bean Validator.