JPA 2.0 EclipseLink检查唯一性 [英] JPA 2.0 EclipseLink Check for unique

查看:327
本文介绍了JPA 2.0 EclipseLink检查唯一性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Exam类中有一个独立的= true ..
我发现因为事务是自动提交所以强制提交我使用
em.commit()



但是我想知道如何检查它是否是唯一的。运行查询不是一个解决方案,因为它可能是检查后的因为可靠性.... / p>

检查uniqness的最佳方法是什么?

  List< Exam_Normal> exam_normals = exam.getExam_Normal(); 
exam.setExam_Normal(null);

试试{
em.persist(考试);
em.flush();

Long i = 0L;
if(exam_normals!= null){
for(Exam_Normal e_n:exam_normals){
i ++;
e_n.setItem(i);
e_n.setId(考试);
em.persist(e_n);
}
}
} catch(例外e){
System.out.print(sfalma--);
}
}

d

解决方案

不幸的是,JPA无法避免因唯一约束违规而导致事务回滚,因为规范要求此Exception标记事务以进行回滚。此外,因为当您使用JPA 2.0 API发出锁定调用时该行可能不存在,锁定调用将无法确保只有锁定线程可以插入该对象。 锁定会阻止更新实体但不会阻止插入。



您需要像在代码中一样执行'persist',但保留为尽可能接近交易的开头,或者让操作在自己的交易中发生。



如果'持久'必须是更大交易的一部分而且未能持久化并不排除应用程序的这一部分成功,然后您应该存储此事务中的实体实例,并且一旦您的应用程序从回滚中恢复,您将能够将它们合并到任何后续事务中。


I have a collumn as unique=true.. in Exam class.... I found that because transactions are commited automaticaly so to force the commit i use em.commit()

However i would like to know how to check if it is unique.Running a query isnt a solution because it may be an instert after checking because of the concurency....

Which is the best way to check for uniqness?

List<Exam_Normal> exam_normals = exam.getExam_Normal();
    exam.setExam_Normal(null);

    try {
        em.persist(exam);
        em.flush();

        Long i = 0L;
        if (exam_normals != null) {
            for (Exam_Normal e_n : exam_normals) {
                i++;
                e_n.setItem(i);
                e_n.setId(exam);
                em.persist(e_n);
            }
        }
    } catch (Exception e) {
        System.out.print("sfalma--");
    }
}

d

解决方案

Unfortunately with JPA there is no way to avoid a transaction rollback upon a Unique Constraint violation as the specification requires this Exception to mark the transaction for rollback. Also, because the row may not exist when you issue the 'lock' call using JPA 2.0 APIs the 'lock' call will not ensure that only the locking thread can insert the object. A 'lock' would prevent the update of the Entity but not the insert.

You would need to perform the 'persist' as you have in your code but keep it as close to the beginning of the transaction as possible or have the operation occur in its own transaction.

If the 'persist' must be part of a larger transaction and the failure to persist does not preclude this part of your application from succeeding then you should store the Entity instances from this transaction and you will be able to 'merge' them into any subsequent transaction once your application recovers from the rollback.

这篇关于JPA 2.0 EclipseLink检查唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆