To know what caused the constraint violation, you can use the following validator and logger.
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Clients>> constraintViolations = validator.validate(clients);
if (constraintViolations.size() > 0 ) {
System.out.println("Constraint Violations occurred..");
for (ConstraintViolation<Clients> contraints : constraintViolations) {
System.out.println(contraints.getRootBeanClass().getSimpleName()+
"." + contraints.getPropertyPath() + " " + contraints.getMessage());
}
}
Put the logger before persisting the entity. So between
em.getTransaction().begin();
//here goes the validator
em.persist(clients);
Compile and run. The console will show you, just before the exception stack trace, which element(s) caused the violation(s).
You can but should catch your try block containing any persistence method with ConstraintViolationException
(to avoid further problems and/or inform the user an error occurred and its reason). However, in a well built system there shouldn't be any constraint violation exception during persistence. In JSF, and other MVC framework, the validation step must be totally or partially done at the client side before submit/persistence. That's a good practice I would say.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…