Home/Learn/Hibernate & JPA/Hibernate Validator (Bean Validation)

Hibernate Validator (Bean Validation)

Intermediate
Advanced

Hibernate Validator is the reference implementation of Jakarta Bean Validation; constraints like @NotNull, @Size, @Email, and @Pattern are enforced on persist and merge.

Overview

Hibernate Validator implements Jakarta Bean Validation (formerly JSR-380). Constraint annotations placed on entity fields are automatically enforced by Hibernate before INSERT (persist) and UPDATE (merge). In Spring, @Valid on a @RequestBody parameter triggers validation before the controller method runs, with @ExceptionHandler for MethodArgumentNotValidException providing structured error responses. Common built-in constraints include @NotNull, @NotBlank (String-specific), @Size(min, max), @Min, @Max, @Email, @Pattern, @Positive, @Future, and @Past. Custom constraints are created with @Constraint + a ConstraintValidator implementation.

Annotating Entities and DTOs

Apply constraint annotations to entity fields or DTO fields. @Valid on nested objects triggers cascaded validation.

Java — Bean Validation constraints on entity
@Entity
public class User {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Name is required")
    @Size(min = 2, max = 100)
    private String name;

    @Email(message = "Invalid email format")
    @NotNull
    @Column(unique = true)
    private String email;

    @Pattern(regexp = "^\\+?[0-9]{10,15}$", message = "Invalid phone number")
    private String phone;

    @Min(value = 0, message = "Age cannot be negative")
    @Max(value = 150)
    private int age;

    @Valid                          // cascade validation into nested object
    @Embedded
    private Address address;
}

Validating in Spring MVC Controllers

@Valid on @RequestBody triggers validation before the controller method. @ExceptionHandler(MethodArgumentNotValidException) converts constraint violations to structured error responses.

Java — @Valid in controller + structured error response
@RestController
@RequestMapping("/users")
public class UserController {

    @PostMapping
    public ResponseEntity<User> create(@Valid @RequestBody CreateUserRequest request) {
        return ResponseEntity.ok(userService.create(request));
    }
}

@RestControllerAdvice
public class ValidationExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidation(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = new LinkedHashMap<>();
        ex.getBindingResult().getFieldErrors()
          .forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
        return ResponseEntity.badRequest().body(errors);
    }
}

Custom Constraint

Create a custom constraint by defining an annotation with @Constraint and a ConstraintValidator implementation. Ideal for cross-field or business-specific rules.

Java — custom @NoProfanity constraint
// Custom annotation
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NoProfanityValidator.class)
public @interface NoProfanity {
    String message() default "Content contains prohibited words";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

// Validator implementation
public class NoProfanityValidator implements ConstraintValidator<NoProfanity, String> {

    private static final Set<String> BANNED = Set.of("spam", "scam");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext ctx) {
        if (value == null) return true;
        String lower = value.toLowerCase();
        return BANNED.stream().noneMatch(lower::contains);
    }
}

// Usage
public class ProductRequest {
    @NoProfanity
    private String description;
}

Key Points to Remember

  • 1Hibernate Validator enforces constraints automatically before JPA persist/merge operations
  • 2@NotNull checks for null; @NotBlank also rejects blank strings — prefer @NotBlank for String
  • 3@Valid in Spring MVC triggers validation before the controller method; @Validated supports groups
  • 4MethodArgumentNotValidException carries all field errors — handle it to return structured JSON
  • 5Custom constraints: define annotation with @Constraint + implement ConstraintValidator<A,T>
  • 6@Valid cascades into @Embedded and nested @Valid-annotated objects

Interview Questions

Sign in to ask Aria
1

What is the difference between @NotNull and @NotBlank?

EasyTCS
2

When is Bean Validation triggered in a JPA lifecycle?

MediumInfosys
3

How do you return a structured list of field errors from a Spring MVC controller?

MediumAmazon
4

How do you create a custom constraint annotation?

HardWipro
5

What is the difference between @Valid and @Validated in Spring?

HardOracle

Ask Aria about Hibernate Validator (Bean Validation)

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…