我有我的代码:
public static Computation findByDateAndPaymentSystem(EntityManager em, Calendar date, PaymentSystem paymentSystem) throws SCException {
Query query = em.createNamedQuery("Computation.findByDateAndPaymentSystem");
query.setParameter("date", date);
query.setParameter("ps", paymentSystem);
List<Computation> computationList = query.getResultList();
if (computationList != null && computationList.size() > 0) {
if (computationList.size() == 1) {
return computationList.get(0);
} else {
throw new SCException("Not unique result in computation for date '"
+ new SimpleDateFormat("dd.MM.yyyy").format(new Date(date.getTimeInMillis())) + "' and paymentSystem = '"
+ paymentSystem.getShortName() + "'");
}
} else {
Computation computation = new Computation();
computation.setDate(date);
computation.setComputationState(ComputationState.CREATED);
computation.setPaymentSystem(paymentSystem);
em.persist(computation);
return computation;
}
}主要的想法是,我应该有一个计算实例,每个日期和支付系统。但如果在两个不同的事务中调用此方法,则可能出现下一种情况:第一个事务检查,如果此日期没有计算并创建计算,但仍未提交创建的计算,则另一个事务检查并创建计算,然后两个事务都提交。因此,每个日期将有两次计算。
如何预防呢?
发布于 2011-11-11 22:15:10
Computation.date和PaymentSystem的组合应该是唯一的(约束),然后第二次插入将失败,或者您可以尝试合并多个条目(如果找到它们)。解决方案取决于您的用例、事务策略和设置。
https://stackoverflow.com/questions/8094402
复制相似问题