@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
。
答案 0 :(得分:1)
您需要实施乐观锁定手动布局。
为每个表添加“版本”列。
在加载和实体..时,您需要加载当前版本
更新实体时,您必须在where子句中添加版本检查并在执行后(int rowCount = st.executeUpdate();
来获取更新的行数
示例:UPDATE ACCOUNT set AMOUNT = x, VERSION = VERSION+1 where ID = XX and VERSION = CURRENT_VERSION
如果更新后的行数为<> 1,则表示该行已被另一个事务(UPDATE或DELETE)修改