嗨,我怀疑如何在合并期间捕获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();
}
但这不会抛出异常,导致a 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();
}
为什么merge没有抛出ConstraintViolationException?我能做些什么来捕捉异常?
谢谢。
答案 0 :(得分:2)
可能为时已晚,但我也遇到了同样的问题。
实际上这在某种程度上是在Hibernate的实现中,请参阅:https://issues.jboss.org/browse/AS7-4576,而https://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;