简体   繁体   English

春季交易回滚UPDATE和INSERT

[英]Spring Transaction roll back both `UPDATE` and `INSERT`

@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);

}

}

In the code above, I would like to rollback both accountDao.updateAmount and orderDao.save if the updated account row is modified by another transaction. 在上面的代码中,如果更新的帐户行被另一笔交易修改,我想同时回滚accountDao.updateAmountorderDao.save 在此处输入图片说明

You need to implement optimistic locking manuallay. 您需要实现乐观锁定手动布局。

Add VERSION column for each table. 为每个表添加“版本”列。

When You load and entity .. you need to load the current version 当您加载和实体..时,您需要加载当前版本

when you update an entity you have to add version check in where clause and get the updated row count after execution ( int rowCount = st.executeUpdate(); ) 更新实体时,您必须在where子句中添加版本检查并在执行后获取更新的行数( int rowCount = st.executeUpdate();

example : UPDATE ACCOUNT set AMOUNT = x, VERSION = VERSION+1 where ID = XX and VERSION = CURRENT_VERSION 示例: UPDATE ACCOUNT set AMOUNT = x, VERSION = VERSION+1 where ID = XX and VERSION = CURRENT_VERSION

If the updated row count is <> 1 it means that the row has been modified by another transaction ( UPDATE or DELETE ) 如果更新的行计数为<> 1,则表示该行已被另一个事务修改(UPDATE或DELETE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM