JPA,Hibernate - 处理包含在RollbackException中的ContraintViolationException

时间:2011-07-24 15:41:56

标签: java hibernate jpa exception-handling

我在JPA2 / Hibernate / Guice环境中处理ConstraintViolationExceptionRollbackException时遇到问题。 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 s:

try {
    // bean validation fails (merge / persist)
} catch (RuntimeException ex) {
    if (errors.process(ex)) {
        // do something with entity
    }
}

是否有可能以某种方式强制hibernate不将CVE包装成RE?处理和处理此类异常的最透明和干燥方式是什么?

由于

1 个答案:

答案 0 :(得分:0)

hibernate将所有sql异常包装为RuntimeException(hibernate的特性)..你得到ConstraintViolationException可能是因为有一些字段不接受空值并且你传递一个空值在插入时...(如果你没有显式设置pojo属性的值,它在插入时被视为null)...

相关问题