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



我在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中?处理和处理这些异常的最透明和DRY的方法是什么?

谢谢

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

相关内容

  • 没有找到相关文章

最新更新