Hello! I am back with a new Blog Post.The title is “Validating Objects using Hibernate Validator Annotations”. I was recently working on a task in which I had to remove the manual validation and use hibernate validation(using annotations) on certain classes. So I am going to explain the basics of hibernate validation.

First we will see that how we can apply constraint on the fields of the class. To apply any constraint we will first need to import the following package like this:-

import javax.validation.constraints.*;

Now we can apply the constraints using the following annotations:-

public class Planet {

@NotNull
private String name;

@NotNull
@Size(min = 2, max = 10)
private String type;  // type of planet

@Min(2)
private int satellites; // Min no. of satellites should be 2

   public Planet(String name, String type, int satellites) {
      this.name = name;
      this.type = type;
      this.satellites = satellites;
   }

   // getters and setters ...
}

The annotations used in the class are used to declare the constraints which should be applied to the attributes of the Planet instance.

  • ‘name’ must not be null
  • ‘type’ must not be null and should be between 2 and 10 characters long
  • ‘satellites’ value must be at least 2

Now as we have declared the constraints we can test it using a simple unit test:-


public class PlanetTest {

private static Validator validator;

   @BeforeClass
   public static void getValidator() {
      ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
      validator = factory.getValidator();
   }

   @Test
   public void test01() {
      Planet planet = new Planet( null, "NewType", 4 );

      Set<ConstraintViolation<Planet>> constraintViolations =
      validator.validate( planet );

      assertEquals( 1, constraintViolations.size() );
      assertEquals(
         "may not be null",
         constraintViolations.iterator().next().getMessage()
      );
   }

   @Test
   public void test02() {
      Planet planet = new Planet( "Saturn", "X", 4 );

      Set<ConstraintViolation<Planet>> constraintViolations =
      validator.validate( planet );

      assertEquals( 1, constraintViolations.size() );
      assertEquals(
         "size must be between 2 and 10",
         constraintViolations.iterator().next().getMessage()
      );
   }

   @Test
   public void test03() {
      Planet planet = new Planet( "Jupiter", "Dwarf", 1 );

      Set<ConstraintViolation<Planet>> constraintViolations =
      validator.validate( planet );

      assertEquals( 1, constraintViolations.size() );
      assertEquals(
         "must be greater than or equal to 2",
         constraintViolations.iterator().next().getMessage()
      );
   }

   @Test
   public void planetIsValid() {
      Planet planet = new Planet( "Earth", "BluePlanet", 2 );

      Set<ConstraintViolation<Planet>> constraintViolations =
      validator.validate( planet );

      assertEquals( 0, constraintViolations.size() );
   }
}

Let us see how the above Unit test Class works:-

The @BeforeClass annotation is used to declare that the method must be called before any test cases are executed.In the getValidator() method a Validator instance is retrieved from the ValidatorFactory.

@Test annotation is used to declare that the method represents a test case. The first test case method test01() creates an instance of Planet Class. It then validates the object using the validate() method which returns a set of ConstraintViolation instances, which we can iterate to see which validation error occurred.The object created in the test01() method violates the NotNull constraint on the “name” field. So we make an assertion to check if the number of violations is equal to 1 and the violation error message is appropriate i.e. “may not be null”.

That was all about Hibernate Validation!

Thanks
Vivek