javax.validation.ConstraintViolationException

后端 未结 2 909
我寻月下人不归
我寻月下人不归 2021-01-01 00:30

I am using JSF+JPA iam not fix this error:

javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Au

2条回答
  •  礼貌的吻别
    2021-01-01 01:27

    To know what caused the constraint violation, you can use the following validator and logger.

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    
    Set> constraintViolations = validator.validate(clients);
    
    if (constraintViolations.size() > 0 ) {
    System.out.println("Constraint Violations occurred..");
    for (ConstraintViolation 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.

提交回复
热议问题