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

标签 java hibernate jpa exception

我在 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:

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/

相关文章:

java - 我不断收到错误。不兼容的类型 : ArrayList<StudentDetails> cannot be converted to ArrayList<AndroidTargets>

java - 我如何处理 Hibernate 中的身份与平等?

java - Hibernate、Oracle、Join Tables 和关键问题

hibernate - JPA:请帮助理解 "join fetch"

java - @OneToOne Hibernate 带注释。无法正确保存

java - 简单的 GridLayout 缩放动画

java - 有什么方法可以让 Spring Data Auditing 根据字段填充 Long 或 String?

java - jdbc 结果集关闭

java - 如何使用 OpenJPA 将对象从一个表 "move"转移到另一个表?

Java EE 持久镜像