spring将事务管理的逻辑和数据访问的逻辑分开管理,但是每一个数据访问dao都需要同一个Connection对象,这时,spring会在事务开始的时候将connection设置到一个ThreadLocal中,在dao中,就从这个ThreadLocal中拿到Connection。
/**
* 声明式事务demo
*/
public void tranfer() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(definition); //设置Connection
try {
String sql = "update tx_account set accountbalance = accountbalance - 20 where userid = 1";
//内部会获取Connection
//Connection con = DataSourceUtils.getConnection(obtainDataSource());
int update = jdbcTemplate.update(sql);
System.out.println(update);
String sql2 = "update tx_account set accountbalance = accountbalance + 20 where userid = 2";
int update2 = jdbcTemplate.update(sql2);
System.out.println(update2);
//throw new RuntimeException();
} catch (Exception e){
transactionManager.rollback(status);
}
transactionManager.commit(status);
}
标签:status,事务,Spring,update,学习,accountbalance,Connection,transactionManager
From: https://www.cnblogs.com/wxmin2/p/17323043.html