我在 JPA2/Hibernate/Guice 环境中处理 ConstraintViolationException
和 RollbackException
时遇到问题。这两个异常都在 bean 验证时发生,但是:
ConstraintViolationException
被抛出
RollbackException
当我尝试将实体合并到上下文中时发生
在表单处理(创建和更新实体)时会发生这种情况,并且捕获这些异常很烦人:
try {
// service.method is annotated with @Transactional
entity = service.create(formEntity);
} catch (RollbackException re) {
// occurs while merging the entity
if (re.getCause() instanceof ConstraintViolationException) {
errors.process((ConstraintViolationException) re.getCause());
}
} catch (ConstraintViolationException cve) {
// occurs while persisting the entity
errors.process(cve);
}
我不想添加另一个控制流并捕获所有RuntimeException
:
try {
// bean validation fails (merge / persist)
} catch (RuntimeException ex) {
if (errors.process(ex)) {
// do something with entity
}
}
是否有可能以某种方式强制 hibernate 不将 CVE 包装到 RE 中?处理和处理此类异常的最透明和最干燥的方式是什么?
谢谢
最佳答案
hibernate将所有sql异常包装为RuntimeException
(hibernate的功能)..您收到ConstraintViolationException
可能是因为有一些字段不接受空值并且您在插入时传递了一个空值。(如果您没有显式设置 pojo 属性的值,则在插入时将其视为空)...
关于java - JPA、Hibernate - 处理包含在 RollbackException 中的 ContraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6807797/