小编Pet*_*oye的帖子

JPA2 唯一约束:我真的需要刷新吗?

我有一个 DAO,我需要在其中捕获唯一的约束异常。为此,唯一可行的解​​决方案是在持久化之后刷新我的 EntityManager。只有这样我才能进入一个catch块,我必须过滤掉异常。而且,我的 DAO 方法需要包含在一个事务中(REQUIRES_NEW),否则我会遇到 RollBackException。

难道我做错了什么?

try {
        em.persist(myObject);
        em.flush();
    } catch (PersistenceException ex) {
        if (ex.getCause() != null) {
            String cause = ex.getCause().toString();
            if (cause != null) {
                if (cause.contains("org.hibernate.exception.ConstraintViolationException")) {
                    logger
                            .error("org.hibernate.exception.ConstraintViolationException: possible unique constraint failure on name");
                    throw ex;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

java orm jpa unique-constraint jpa-2.0

5
推荐指数
1
解决办法
3630
查看次数

标签 统计

java ×1

jpa ×1

jpa-2.0 ×1

orm ×1

unique-constraint ×1