Hibernate Validator CDI – @HibernateValidator Example

Java example of hibernate validator CDI to inject default Java bean validation classes implementations e.g. javax.validation.ValidatorFactory and javax.validation.Validator with hibernate-validator-cdi dependency. Also learn to inject specialized validator if application has multiple validator implementations like org.hibernate.validator.cdi.HibernateValidator.

Please note that if your application runs in an environment which provides this integration out of the box, then you do not need to add additional dependencies to run this example. For example, spring framework provides such CDI infrastructure implicitly, so don’t use hibernate validator CDI with Spring framework.

For other applications, such as standalone Java applications, you may need it to create HibernateValidator using annotations.

1. Hibernate Validator CDI Maven Dependency

All necessary dependencies to work with hibernate validator are listed below.

<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.howtodoinjava.example</groupId>
	<artifactId>hibernate-validator</artifactId>
	<version>0.0.1</version>
	<packaging>jar</packaging>

	<name>hibernate-validator</name>
	<url>http://maven.apache.org</url>

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

	<dependencies>
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>2.0.1.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate.validator</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>6.0.11.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate.validator</groupId>
			<artifactId>hibernate-validator-cdi</artifactId>
			<version>6.0.11.Final</version>
		</dependency>
		<dependency>
			<groupId>javax.el</groupId>
			<artifactId>javax.el-api</artifactId>
			<version>3.0.1-b06</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.web</groupId>
			<artifactId>javax.el</artifactId>
			<version>2.2.6</version>
		</dependency>
	</dependencies>
</project>

2. Model class annotated with validation annotations

A simple Java class with field validation annotations.

package com.howtodoinjava.example.model;

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

public class User {

    @NotNull(message = "Please enter id")
    private Long id;

    @Size(max = 20, min = 3, message = "{user.name.invalid}")
    @NotEmpty(message = "Please enter name")
    private String name;

    @Email(message = "{user.email.invalid}")
    @NotEmpty(message = "Please enter email")
    private String email;

    public User(Long id, String name, String email) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
    }

	//Getters and Setters

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", email=" + email + "]";
    }
}

3. Inject default and hibernate javax.validation.Validator

Inject ValidatorFactory and Validator using @Inject annotations. The injected beans are the default validator factory and validator instances.

@Inject
private static ValidatorFactory validatorFactory;

@Inject
private static Validator validator;

If you are working with several Bean Validation providers, you can make sure that factory and validator from Hibernate Validator are injected by annotating the injection points with the @HibernateValidator qualifier.

import org.hibernate.validator.cdi.HibernateValidator;


@Inject
@HibernateValidator
private static ValidatorFactory validatorFactory;

@Inject
@HibernateValidator
private static Validator validator;

4. How to validate beans

An example to use injected validator to validate Java beans and check error messages.

package com.howtodoinjava.example;

import java.util.Set;

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

import org.hibernate.validator.cdi.HibernateValidator;

import com.howtodoinjava.example.model.User;

public class TestHibernateValidator 
{
    @Inject
    @HibernateValidator
    private static ValidatorFactory validatorFactory;

    @Inject
    @HibernateValidator
    private static Validator validator;
    
    public static void main(String[] args) 
    {
        //Create ValidatorFactory which returns validator
        validatorFactory = Validation.buildDefaultValidatorFactory();
        
        //It validates bean instances
        validator = validatorFactory.getValidator();

        User user = new User(null, "1", "abcgmail.com");

        //Validate bean
        Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);

        //Show errors
        if (constraintViolations.size() > 0) {
            for (ConstraintViolation<User> violation : constraintViolations) {
                System.out.println(violation.getMessage());
            }
        } else {
            System.out.println("Valid Object");
        }
    }
}

Program output:

Aug 06, 2018 12:25:17 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 6.0.11.Final

Please enter id
'1' is an invalid name. It must be minimum 3 chars and maximum 20 chars.
Invalid Email

Above example fetches resource messages from property file in classpath.

user.name.invalid='${validatedValue}' is an invalid name. It must be minimum {min} chars and maximum {max} chars.
user.email.invalid=Invalid Email

5. Summary

In above example, we learn the following:

  • How we can include hibernate validator CDI dependency and use it.
  • How to inject default validator factory and validator instances.
  • How to inject specialized validator factory and validator instances, if there are more than one Java bean validator implementations. e.g. in above case, it’s hibernate validator.
  • How to validate Java beans using annotations configuration.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.