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
