假设我在表“X”上有这些数据:
ID UpdatedDate ParentID
001 2015-01-01 1
002 1
003 1
代码是(我简化了代码):
...
@Autowired
private XDao xDao;
private void createTransaction(ParentData parentData) {
List<XData> xDataList = xDao.getDataByParentIdAndUpdatedDateIsNull(parentData.getId());
XData xData = null;
// Then we get only the first row of the list
if(xDataList != null && xDataList.size() > 0) {
xData = xDataList.get(0);
} else {
return;
}
// Another transaction
...
// Then we update the UpdatedDate
xData.setUpdatedDate(new Date());
xDao.saveAndFlush(xData);
// And we call the createTransaction again until there is no more xData with a null UpdatedDate on a Parent ID
createTransaction(parentData);
}
但是我得到的是一个永无止境的过程,当我检查数据库时,它总是会影响同一父 ID 上的彼此数据。所以数据库是这样的:
第一次迭代:
ID UpdatedDate ParentID
001 2015-01-01 1
002 2015-02-02 1
003 1
第二个:
ID UpdatedDate ParentID
001 2015-01-01 1
002 1
003 2015-02-02 1
第三个:
ID UpdatedDate ParentID
001 2015-01-01 1
002 2015-02-02 1
003 1
等等。怎么了?
<小时/>这是 getDataByParentIdAndUpdatedDateIsNull 类(我简化了代码):
...
public static final String GET_DATA_BY_PARENTIDANDUPDATEDDATEISNULL =
"SELECT o FROM XData o " +
"WHERE o.parentData.parentId = ?1 " +
" AND o.updatedDate IS NULL";
@Query(GET_DATA_BY_PARENTIDANDUPDATEDDATEISNULL)
public List<XData> getDataByParentIdAndUpdatedDateIsNull(Long parentId);
最佳答案
可以分享吗
1) XDao
的定义
2)您的底层数据存储是什么
3)您是否使用任何 ORM 框架
4) 您是否在存储库/服务或 tx:annotation-driven
上使用显式 @Transactional
?
根据上述组合,行为会有所不同,但我的猜测是服务事务边界与存储事务边界混淆,或者由于 @Transactional
机制基于代理,因此只有通过代理传入的“外部”方法调用才会被拦截,并且您的递归调用不会通过您可能为 createTransaction
方法设置的相同 AOP。
话虽如此,是否不能做这样的事情而不是递归:
for (XData xData : xDataList) {
xData.setUpdatedDate(new Date());
xData.saveAndFlush(xData);
}
关于java - 新持久化后,之前持久化的数据总是会重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30721335/