我有代码:
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;
}
}
主要想法是我应该为每个日期和支付系统分配一个计算实例。 但如果在两个不同的事务中调用此方法,则可能出现以下情况: 第一个事务检查,如果该日期没有计算并创建计算但仍未提交创建的计算,另一个事务检查并也创建计算,则两个事务都提交。因此,每个日期都会进行两次计算。
如何预防?
最佳答案
Computation.date
和 PaymentSystem
组合应该是唯一的(约束),然后第二次插入将失败,或者如果找到多个条目,您可以尝试合并多个条目。解决方案取决于您的用例以及事务策略和设置。
关于java - 用于读取的 JPA 锁定实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8094402/