@Service
@Transactional
public class OrderService {
//Implemented with JdbcTemplate (no ORM)
//Both Dao use the same DataSource
private AccountDao accountDao;
private OrderDao orderDao;
public void update(int accountId){
//Get account and do some calculation (simplifed version here)
Account account = accountDao.findByid(accountId)
int newAmount = account.getAmoount * 100;
//Update account table
accountDao.updateAmount(accountId, newAmount);
//Insert new order
Order order = ....
orderDao.save(order);
}
}
在上面的代码中,如果更新的帐户行被另一个事务修改,我想回滚 accountDao.updateAmount
和 orderDao.save
。
最佳答案
您需要手动实现乐观锁定。
为每个表添加 VERSION 列。
当您加载实体时..您需要加载当前版本
当您更新实体时,您必须在 where 子句中添加版本检查并在执行后获取更新的行计数 ( int rowCount = st.executeUpdate();
)
示例:更新帐户设置 AMOUNT = x、VERSION = VERSION+1,其中 ID = XX 且 VERSION = CURRENT_VERSION
如果更新的行计数为 <> 1,则表示该行已被另一个事务( UPDATE 或 DELETE )修改
关于java - Spring事务回滚 `UPDATE`和 `INSERT`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55004463/