liveBook · Manning

ConstraintViolationException

As explained in Java Persistence with Spring Data and Hibernate epub

ConstraintViolationException is an exception reporting one or more failed Bean Validation constraints during persistence operations.

ConstraintViolationException reports one or more failed Bean Validation constraints when Hibernate validates a persistent entity before database insertion or update. Its failure details let calling code identify the rejected constraints. section 3.3.2

Control and diagnose automatic validation through the persistence configuration:

  • AUTO validates when a Bean Validation provider is available on the runtime classpath. section 3.3.2
  • CALLBACK requires validation and fails deployment if the provider is missing; NONE disables provider-triggered validation. section 3.3.2
  • Inspect the exception's failure details to determine which constraint rejected the entity. section 3.3.2
Listing 3.7 Testing an Item instance for constraint violations
Path: Ch03/validation/src/test/java/com/manning/javapersistence/ch03
 /validation/ModelValidation.java
 
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
 
Item item = new Item();
item.setName("Some Item");
item.setAuctionEnd(new Date());
 
Set<ConstraintViolation<Item>> violations = validator.validate(item);
 
ConstraintViolation<Item> violation = violations.iterator().next();
String failedPropertyName =
        violation.getPropertyPath().iterator().next().getName();
 
// Validation error, auction end date was not in the future!
assertAll(() -> assertEquals(1, violations.size()),
        () -> assertEquals("auctionEnd", failedPropertyName),
        () -> {
            if (Locale.getDefault().getLanguage().equals("en"))
                assertEquals(violation.getMessage(),
                             "must be a future date");
        });

Shows programmatic validation of an Item instance and extraction of the failed property name before persistence. section 3.3.2

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains triggering, failure details, and validation-mode configuration, but does not detail exception-handling code.
Examples
Uses Item constraints such as @NotNull, @Size, and @Future, plus programmatic violation inspection.
What it assumes
Assumes Bean Validation annotations and persistence operations, while demonstrating provider discovery and validation callbacks.
What you can do after
Diagnose rejected entities by inspecting constraint-violation details and configure automatic validation behavior.
How it connects
Connects Bean Validation, Hibernate Validator, JPA, persistent domain models, and SQL schema constraints.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.