Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Hibernate Bean Validator in Java SE

DZone's Guide to

Using Hibernate Bean Validator in Java SE

Learn how to use the Bean Validation outside of your Java EE container.

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

The main Bean Validation page states that "Bean Validation is a Java specification which ... runs in Java SE but is integrated in Java EE (6 and 7)." This post demonstrates using Java Bean Validation reference implementation (Hibernate Validator) outside of a Java EE container. The examples in this post are based onHibernate Validator 5.1.3 Final, which can be downloaded at http://hibernate.org/validator/downloads.

"Getting Started with Hibernate Validator" states that Hibernate Validator requires implementations ofUnified Expression Language (JSR 341) and Contexts and Dependency Injection (CDI/JSR 346). Implementations of these specifications are available in modern Java EE compliant containers (application servers), but use of Hibernate Validator in Java SE environments requires procurement and use of separate implementations.

The "Getting Started with Hibernate Validator" page provides the Maven XML one can use to identify dependencies on the Expression Language API (I'm using Expression Language 3.0 API), Expression Language Implementation (I'm using Expression Language Implementation 2.2.6), and Hibernate Validator CDI portable extension (I'm using Hibernate Validator Portable Extension 5.1.3 Final). I am also using Bean Validation API 1.1.0 FinalJBoss Logging 3.3.0 Final, and ClassMate 1.2.0 to build and run my examples.

There are three Java classes defined for the examples of bean validation demonstrated in this post. One class, Car.java is adapted from the example provided on the "Getting started with Hibernate Validator" page and its code listing is shown next.

Car.java

package dustin.examples;

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

/**
 * Example adapted from "Getting Started with Hibernate Validator"
 * (http://hibernate.org/validator/documentation/getting-started/).
 */
public class Car
{
   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

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

   public String getManufacturer()
   {
      return manufacturer;
   }

   public String getLicensePlate()
   {
      return licensePlate;
   }

   public int getSeatCount()
   {
      return seatCount;
   }

   @Override
   public String toString()
   {
      return "Car{" +
         "manufacturer='" + manufacturer + '\'' +
         ", licensePlate='" + licensePlate + '\'' +
         ", seatCount=" + seatCount +
         '}';
   }
}

Another class used in this post's examples is defined in Garage.java and is mostly a wrapper of multiple instances of Car. Its primary purpose is to help illustrate recursive validation supported by Hibernate Bean Validator.

Garage.java

package dustin.examples;

import javax.validation.Valid;
import javax.validation.constraints.Size;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * Holds cars.
 */
public class Garage
{
   @Size(min = 1)
   @Valid
   private final Set<Car> cars = new HashSet<>();

   public Garage() {}

   public void addCar(final Car newCar)
   {
      cars.add(newCar);
   }

   public Set<Car> getCars()
   {
      return Collections.unmodifiableSet(this.cars);
   }
}

The Garage code listing above uses the @Valid annotation to indicate that the Car instances held by the class should also be validated ("validation cascading").

The final Java class used in this post's examples is the class that will actually perform the validation of the two bean validation annotated classes Car and Garage. This class's listing is shown next.

HibernateValidatorDemonstration.java

package dustin.examples;

import static java.lang.System.out;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.Validator;
import java.util.Set;

/**
 * Demonstrate use of Hibernate Validator.
 */
public class HibernateValidatorDemonstration
{
   private final Validator validator;

   public HibernateValidatorDemonstration()
   {
      final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
      validator = factory.getValidator();
   }

   public void demonstrateValidator()
   {
      final Car nullManufacturerCar = new Car(null, "ABC123", 4);
      final Set<ConstraintViolation<Car>> nullMfgViolations = validator.validate(nullManufacturerCar);
      printConstraintViolationsToStandardOutput("Null Manufacturer Example", nullMfgViolations);

      final Car nullLicenseCar = new Car("Honda", null, 3);
      final Set<ConstraintViolation<Car>> nullLicenseViolations = validator.validate(nullLicenseCar);
      printConstraintViolationsToStandardOutput("Null License Example", nullLicenseViolations);

      final Car oneSeatCar = new Car("Toyota", "123ABC", 1);
      final Set<ConstraintViolation<Car>> tooFewSeatsViolations = validator.validate(oneSeatCar);
      printConstraintViolationsToStandardOutput("Too Few Seats Example", tooFewSeatsViolations);

      final Car oneDigitLicenseCar = new Car("General Motors", "I", 2);
      final Set<ConstraintViolation<Car>> tooFewLicenseDigitsViolation = validator.validate(oneDigitLicenseCar);
      printConstraintViolationsToStandardOutput("Too Few License Digits Example", tooFewLicenseDigitsViolation);

      final Car nullManufacturerNullLicenseCar = new Car(null, null, 4);
      final Set<ConstraintViolation<Car>> nullMfgLicenseViolation = validator.validate(nullManufacturerNullLicenseCar);
      printConstraintViolationsToStandardOutput("Null Manufacturer and Null License Example", nullMfgLicenseViolation);

      final Garage garage = new Garage();
      final Set<ConstraintViolation<Garage>> noCarsInGarage = validator.validate(garage);
      printConstraintViolationsToStandardOutput("No Cars in Garage", noCarsInGarage);

      garage.addCar(oneDigitLicenseCar);
      garage.addCar(oneSeatCar);
      garage.addCar(nullManufacturerNullLicenseCar);
      final Set<ConstraintViolation<Garage>> messedUpCarsInGarage = validator.validate(garage);
      printConstraintViolationsToStandardOutput("Messed Up Cars in Garage", messedUpCarsInGarage);
   }

   private <T> void printConstraintViolationsToStandardOutput(
      final String title,
      final Set<ConstraintViolation<T>> violations)
   {
      out.println(title);
      for (final ConstraintViolation<T> violation : violations)
      {
         out.println("\t" + violation.getPropertyPath() + " " + violation.getMessage());
      }
   }

   public static void main(final String[] arguments)
   {
      final HibernateValidatorDemonstration instance = new HibernateValidatorDemonstration();
      instance.demonstrateValidator();
   }
}

The above code features several calls to javax.validation.Validator.validate(T, Class<?>) that demonstrate the effectiveness of the annotations on the classes whose instances are being validated. Several examples validate an object's single validation violation, an example validates an object's multiple validation violations, and a final example demonstrates successful cascading violation detection.

The class HibernateValidatorDemonstration has a main(String[]) function that can be executed in a Java SE environment (assuming the necessary JARs are on the runtime classpath). The output of running the above demonstration class is shown next:

Jul 19, 2015 9:30:05 PM org.hibernate.validator.internal.util.Version 
INFO: HV000001: Hibernate Validator 5.1.3.Final
Null Manufacturer Example
 manufacturer may not be null
Null License Example
 licensePlate may not be null
Too Few Seats Example
 seatCount must be greater than or equal to 2
Too Few License Digits Example
 licensePlate size must be between 2 and 14
Null Manufacturer and Null License Example
 manufacturer may not be null
 licensePlate may not be null
No Cars in Garage
 cars size must be between 1 and 2147483647
Messed Up Cars in Garage
 cars[].licensePlate size must be between 2 and 14
 cars[].manufacturer may not be null
 cars[].licensePlate may not be null
 cars[].seatCount must be greater than or equal to 2

Conclusion

This post has demonstrated that the Hibernate Bean Validator, the reference implementation of the Bean Validation specification, can be executed in a Java SE environment. As part of this demonstration, some basic concepts associated with the Bean Validation specification and the Hibernate Bean Validator implementation were also discussed and demonstrated.

Additional Resources

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
hibernate

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}