Hibernate Validator



An validator tool for easy validation of several fields of the class.
This utility will help you avoid ample no of if else conditions that are usually added in the code to validate the input. This helps avoiding a lot of boiler plate code. Simply perform validations with annotations. 

Mvn Dependency :

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
   <version>5.4.1.Final</version>
</dependency>

For a stand alone application the below 2 dependencies may also need to be added. 

<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>

Sample Code : 

package com.arraysprob;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Car {

   @NotNull(message=" manufacturer Name cannot be null")
   private String manufacturer;

   @NotNull(message=" licensePlate Name cannot be null min 2 and max 14")
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   public Car(String manufacturer, String licencePlate, int seatCount) {
      this.manufacturer = manufacturer;
      this.licensePlate = licencePlate;
      this.seatCount = seatCount;
   }
}

Main Method

import java.util.Set;

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

public class HibernateValidator {

   public static void main(String[] agrs) {
      System.out.println("hello");
      Car car = new Car(null, "DD-AB-123", 4);
      ValidatorFactory validatorFactory = Validation
            .buildDefaultValidatorFactory();
      Validator validator = validatorFactory.getValidator();

      Set<ConstraintViolation<Car>> constraintValidation = validator
            .validate(car);

      for (ConstraintViolation<Car> error : constraintValidation) {
         System.out.println(error.getMessageTemplate() + "::" + error.getPropertyPath() + "::" + error.getMessage());

      }
   }

}

Comments