在 spring 中大部分时候使用的是声明式事务,也就是 @Transaction 注解,但在某些特殊情况下也需要手动控制事务的开启/提交/回滚。
工具类封装:
1 @Component 2 public class TransactionUtils { 3 @Resource 4 private DataSourceTransactionManager transactionManager; 5 6 //开启事务,传入隔离级别 7 public TransactionStatus begin(int isolationLevel) { 8 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); 9 // 事物隔离级别,开启新事务 TransactionDefinition.ISOLATION_READ_COMMITTED 10 def.setIsolationLevel(isolationLevel); 11 // 事务传播行为 12 def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); 13 //默认事务 14 TransactionStatus transaction = transactionManager.getTransaction(def); 15 //将拿到的事务返回进去,才能提交。 16 return transaction; 17 } 18 19 //提交事务 20 public void commit(TransactionStatus transaction) { 21 //提交事务 22 transactionManager.commit(transaction); 23 } 24 25 //回滚事务 26 public void rollback(TransactionStatus transaction) { 27 transactionManager.rollback(transaction); 28 } 29 }
使用:
1 // 手动开启事务 2 TransactionStatus transaction = transactionUtils.begin(TransactionDefinition.ISOLATION_READ_COMMITTED); 3 try { 4 // 修改数据回写 5 6 // 手动提交事务 7 transactionUtils.commit(transaction); 8 } catch (Exception e) { 9 // 手动回滚事务 10 transactionUtils.rollback(transaction); 11 }
标签:事务,transaction,Spring,手动,transactionManager,public,TransactionStatus From: https://www.cnblogs.com/niuyourou/p/16899554.html