Hibernate Tutorial

Core Hibernate

Hibernate Mapping

Hibernate Annotations

Hibernate with Spring Framework

Hibernate with Database

Hibernate Log4j

Inheritance Mapping

Hibernate Validator with Example

Hibernate Validator is an implementation of the Java Bean Validation (JSR 380) specification. It allows developers to ensure that the objects' state meets the right criteria, using annotations. In essence, you can use it to ensure that the data state of your objects is valid.

Setting Up

  • Add the necessary dependencies. For Maven:
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.5.Final</version>
</dependency>
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.el</artifactId>
    <version>3.0.1-b09</version>
</dependency>
  • For the validation API:
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>

Simple Validation Example

  • Create a Java class User with some validation rules:
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {

    @NotNull(message = "Name cannot be null")
    @Size(min = 2, max = 30, message = "Name must be between 2 and 30 characters")
    private String name;

    @NotNull
    @Email(message = "Email should be valid")
    private String email;

    @Min(value = 18, message = "Age should be above 18")
    private int age;

    // Getters, setters, constructors...
}
  • Validate the User instance:
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public class HibernateValidatorExample {
    
    public static void main(String[] args) {
        User user = new User("A", "invalidemail", 15);

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        Set<ConstraintViolation<User>> violations = validator.validate(user);
        for (ConstraintViolation<User> violation : violations) {
            System.out.println(violation.getMessage());
        }
    }
}

When you run the above code, it will print validation messages like:

Name must be between 2 and 30 characters
Email should be valid
Age should be above 18

Custom Validation

  • Create a custom annotation:
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {ValidPasswordValidator.class})
public @interface ValidPassword {
    String message() default "Invalid Password";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
  • Implement the validation logic:
public class ValidPasswordValidator implements ConstraintValidator<ValidPassword, String> {
    
    @Override
    public void initialize(ValidPassword constraintAnnotation) {
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // Add your password validation logic here
        return value != null && value.matches("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$");
    }
}
  • Use the custom validation in your entity:
public class User {
    
    @ValidPassword
    private String password;

    // ... other fields, getters, setters, etc.
}

Conclusion

Hibernate Validator is a powerful tool for validating Java beans, providing a vast range of default constraints and the flexibility to define custom validations. Integrating it with frameworks like Spring Boot can further streamline the validation process across your application.

  1. Configuring Hibernate Validator in a project:

    • To configure Hibernate Validator in a project, include the hibernate-validator dependency in your project's build file (e.g., Maven or Gradle).
    • Here's a Maven example:
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>7.0.2.Final</version>
    </dependency>
    
    • Ensure the Bean Validation API is also included in the project.
  2. Annotation-based validation in Hibernate:

    • Use annotations from the javax.validation.constraints package for validation.
    • Example:
    public class Person {
        @NotBlank
        private String name;
    
        @Min(18)
        private int age;
    
        // Getters and setters
    }
    
  3. Custom constraints with Hibernate Validator:

    • Create custom constraints by implementing the ConstraintValidator interface.
    • Example:
    @Target({ ElementType.FIELD, ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = MyCustomValidator.class)
    public @interface MyCustomConstraint {
        String message() default "Invalid value";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    }
    
    public class MyCustomValidator implements ConstraintValidator<MyCustomConstraint, String> {
        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            // Custom validation logic
            return /* validation result */;
        }
    }
    
  4. Validating entities and DTOs with Hibernate Validator:

    • Apply validation annotations to fields or methods in entities or DTOs.
    • Use the Validator to perform validation.
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    Set<ConstraintViolation<Person>> violations = validator.validate(person);
    
  5. Grouping and sequencing validations in Hibernate Validator:

    • Group constraints and define their order using validation groups.
    • Example:
    public interface BasicValidationGroup {}
    
    public interface AdvancedValidationGroup {}
    
    public class Person {
        @NotBlank(groups = BasicValidationGroup.class)
        private String name;
    
        @Min(value = 18, groups = AdvancedValidationGroup.class)
        private int age;
    }
    
  6. Using message interpolation in Hibernate Validator:

    • Customize validation error messages using message interpolation.
    • Example:
    @NotBlank(message = "{custom.message}")
    private String name;
    
    • Define the message in a ValidationMessages.properties file.
  7. Integration of Hibernate Validator with Spring:

    • Spring Boot automatically configures Hibernate Validator.
    • Add spring-boot-starter-validation to the dependencies.
    • Example:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    
    • Use @Validated and @Valid annotations in Spring controllers.