ConstraintViolationException

ConstraintViolationException

嗨,我怀疑如何在合并过程中捕获ConstraintViolationException。我有我的JPALogic类,我想捕获该异常以记下更多信息,此代码可以完美运行,并抛出GenericSaveException:

try {
  em.persist(o);
} catch (ConstraintViolationException e) {
  System.out.println("*** CONSTRAINT VIOLATIONS");
  Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
  for (ConstraintViolation<?> violation : violations) {
    System.err.println("*** VIOLATION: " + violation.getRootBeanClass().getSimpleName() + "::" + violation.getPropertyPath().toString() + " " + violation.getMessage());
  }
  throw new GenericSaveException();
}

但这不会引发异常,从而导致
javax.ejb.EJBException:事务中止,原因:javax.transaction.RollbackException:标记为回滚的事务,原因:javax.validation.ConstraintViolationException:

try {
  managed = (T) em.merge(o);
} catch (ConstraintViolationException e) {
  System.out.println("*** JPALogic::merge --> CONSTRAINT VIOLATIONS");
  Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
  for (ConstraintViolation<?> violation : violations) {
    System.err.println("*** VIOLATION: " + violation.getRootBeanClass().getSimpleName() + "::" + violation.getPropertyPath().toString() + " " + violation.getMessage());
  }
  throw new GenericSaveException();
}

为什么合并不会引发ConstraintViolationException?我该怎么办才能捕捉到异常?

谢谢。

最佳答案

可能为时已晚,但我也面临同样的问题。

实际上,这是在Hibernate的实现中以某种方式实现的,请参见:https://issues.jboss.org/browse/AS7-4576https://hibernate.atlassian.net/browse/HHH-7288说它无法修复。可能此功能(首次调用时进行验证)将在EclipseLink上起作用,但我还没有尝试过。

为了解决此问题,我在服务层中使用了一些更改后的逻辑,在调用merge或persist之前,请运行以下命令:

Set<ConstraintViolation<Contact>> validations = validator.validate(data);
if (validations.size() > 0) {
    Map<String, String> messages = new HashMap<>();
    for (ConstraintViolation v : validations) {
        messages.put(v.getPropertyPath().toString(), v.getMessage());
    }

    return Response.status(Response.Status.BAD_REQUEST).entity(messages).build();
}

验证器是在我的bean中进行简单注入的地方:
@Inject
Validator validator;

07-26 06:22