Spring编程式事务 Spring源码解析之编程式事务
星夜孤帆 人气:0一、前言
在Spring中,事务有两种实现方式:
编程式事务管理: 编程式事务管理使用TransactionTemplate可实现更细粒度的事务控制。声明式事务管理: 基于Spring AOP实现。其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。声明式事务管理不需要入侵代码,通过@Transactional就可以进行事务操作,更快捷而且简单(尤其是配合spring boot自动配置,可以说是精简至极!),且大部分业务都可以满足,推荐使用。
其实不管是编程式事务还是声明式事务,最终调用的底层核心代码是一致的。本文主要介绍编程式事务的一些应用,以及独有的源码分析,再在其他文章中进入核心源码贯穿式讲解。
二、编程式事务解析
编程式事务,Spring已经给我们提供好了模板类TransactionTemplate,可以很方便的使用,如下图:
TransactionTemplate全路径名是:org.springframework.transaction.support.TransactionTemplate。看包名也知道了这是spring对事务的模板类。(spring动不动就是各种Template...),看下类图先:
实现了TransactionOperations、InitializingBean这2个接口(熟悉spring源码的知道这个InitializingBean又是老套路),我们来看下接口源码如下:
public interface TransactionOperations { @Nullable <T> T execute(TransactionCallback<T> action) throws TransactionException; } public interface InitializingBean { void afterPropertiesSet() throws Exception; }
如上图,TransactionOperations这个接口用来执行事务的回调方法,InitializingBean这个是典型的spring bean初始化流程中的预留接口,专用用来在bean属性加载完毕时执行的方法。
回到正题,TransactionCallback和TransactionCallbackWithoutResult做了什么
@FunctionalInterface public interface TransactionCallback<T> { @Nullable T doInTransaction(TransactionStatus status); } public abstract class TransactionCallbackWithoutResult implements TransactionCallback<Object> { @Override @Nullable public final Object doInTransaction(TransactionStatus status) { doInTransactionWithoutResult(status); return null; } protected abstract void doInTransactionWithoutResult(TransactionStatus status); }
可见TransactionCallbackWithResult实现了TransactionCallback接口,重写了doIntransaction方法,在内部调用了doInTransactionWithoutResult方法,帮我们返回了null,所以,我们就不需要再指定返回值了。
TransactionTemplate的2个接口的impl方法做了什么?
@Override public void afterPropertiesSet() { if (this.transactionManager == null) { throw new IllegalArgumentException("Property 'transactionManager' is required"); } } @Override public <T> T execute(TransactionCallback<T> action) throws TransactionException { // 内部封装好的事务管理器 if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) { return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action); }// 需要手动获取事务,执行方法,提交事务的管理器 else {// 1.获取事务状态 TransactionStatus status = this.transactionManager.getTransaction(this); T result; try {// 2.执行业务逻辑 result = action.doInTransaction(status); } catch (RuntimeException ex) { // 应用运行时异常 -> 回滚 rollbackOnException(status, ex); throw ex; } catch (Error err) { // Error异常 -> 回滚 rollbackOnException(status, err); throw err; } catch (Throwable ex) { // 未知异常 -> 回滚 rollbackOnException(status, ex); throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception"); }// 3.事务提交 this.transactionManager.commit(status); return result; } }
如上图所示,实际上afterPropertiesSet只是校验了事务管理器不为空,execute()才是核心方法,execute主要步骤:
1.getTransaction()获取事务
2.doInTransaction()执行业务逻辑,这里就是用户自定义的业务代码。如果是没有返回值的,就是doInTransactionWithoutResult()。
3.commit()事务提交:调用AbstractPlatformTransactionManager的commit,rollbackOnException()异常回滚:调用AbstractPlatformTransactionManager的rollback(),事务提交回滚。源码见后续文章
三、编程式事务示例
public class SpringTransactionExample { private static String url = "jdbc:mysql://localhost:3306/spring_transaction?useSSL=false&characterEncoding=utf-8&autoReconnect=true"; private static String user = "root"; private static String password = "root"; public static void main(String[] args) { // 获取数据源 final DataSource ds = new DriverManagerDataSource(url, user, password); // 编程式事务 final TransactionTemplate template = new TransactionTemplate(); // 设置事务管理器 template.setTransactionManager(new DataSourceTransactionManager(ds)); template.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus transactionStatus) { Connection conn = DataSourceUtils.getConnection(ds); Object savePoint = null; try { { // 插入 PreparedStatement prepare = conn.prepareStatement("insert into person(id, name) values (?, ?)"); prepare.setString(1, "1"); prepare.setString(2, "1111"); prepare.executeUpdate(); } // 设置保存点,回滚的化,不会回滚保存点之前的操作 savePoint = transactionStatus.createSavepoint(); { // 插入 PreparedStatement prepare = conn.prepareStatement("insert into person(id, name) values (?, ?)"); prepare.setString(1, "2"); prepare.setString(2, "222"); prepare.executeUpdate(); } { // 更新 PreparedStatement prepare = conn.prepareStatement("update person set name = ? where id = ?"); prepare.setString(1, "jak"); prepare.setInt(2, 6); prepare.executeUpdate(); // 模拟异常 // int i = 1 / 0; } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { System.out.println("更新失败"); if (savePoint != null) { // 回滚到保存点 transactionStatus.rollbackToSavepoint(savePoint); } else { transactionStatus.setRollbackOnly(); } } return null; } }); } }
四、TransactionCallback
编程式事务带返回值
public class TransactionCallBackTest { private static String url = "jdbc:mysql://localhost:3306/spring_transaction?useSSL=false&characterEncoding=utf-8&autoReconnect=true"; private static String user = "root"; private static String password = "root"; public static void main(String[] args) { // 获取数据源 final DataSource ds = new DriverManagerDataSource(url, user, password); // 编程式事务 final TransactionTemplate template = new TransactionTemplate(); // 设置事务管理器 template.setTransactionManager(new DataSourceTransactionManager(ds)); Connection connection = DataSourceUtils.getConnection(ds); test1(template, connection); test2(template, connection); } // 方式一: 匿名内部类 @SuppressWarnings("all") public static void test1(TransactionTemplate template, Connection connection) { // TransactionCallback有返回值 template.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { try { // 插入 PreparedStatement prepare = connection.prepareStatement("insert into person(id, name) values (?, ?)"); prepare.setInt(1, 1); prepare.setString(2, "jak"); prepare.executeUpdate(); // 模拟异常 // int i = 1 / 0; System.out.println("数据已插入"); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { System.out.println("更新失败"); status.setRollbackOnly(); } return null; } }); } // 方式二:lamda表达式 @SuppressWarnings("all") public static void test2(TransactionTemplate template, Connection connection) { template.execute((status) -> { try { // 插入 PreparedStatement prepare = connection.prepareStatement("insert into person(id, name) values (?, ?)"); prepare.setInt(1, 2); prepare.setString(2, "hyd"); prepare.executeUpdate(); // 模拟异常 // int i = 1 / 0; System.out.println("数据已插入"); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { System.out.println("更新失败"); status.setRollbackOnly(); } return null; }); } }
五、TransactionCallbackWithoutResult
编程式事务不带返回值
public class TransactionCallbackWithoutResultTest { private static String url = "jdbc:mysql://localhost:3306/spring_transaction?useSSL=false&characterEncoding=utf-8&autoReconnect=true"; private static String user = "root"; private static String password = "root"; @SuppressWarnings("all") public static void test(TransactionTemplate template, Connection connection) { template.execute(new TransactionCallbackWithoutResult() { // doInTransactionWithoutResult无返回值 @Override public void doInTransactionWithoutResult(TransactionStatus status) { try { // 插入 PreparedStatement prepare = connection.prepareStatement("insert into person(id, name) values (?, ?)"); prepare.setInt(1, 1); prepare.setString(2, "jak"); prepare.executeUpdate(); // 模拟异常 // int i = 1 / 0; System.out.println("数据已插入"); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { System.out.println("更新失败"); status.setRollbackOnly(); } } }); } public static void main(String[] args) { // 获取数据源 final DataSource ds = new DriverManagerDataSource(url, user, password); // 编程式事务 final TransactionTemplate template = new TransactionTemplate(); // 设置事务管理器 template.setTransactionManager(new DataSourceTransactionManager(ds)); Connection connection = DataSourceUtils.getConnection(ds); test(template, connection); } }
踩坑指南,上述方式 不知道为啥,事务一直不回滚,改为jdbcTemplate方式,可以正常回滚,不知道什么原因
public class jdbcTemplateTest { private static String url = "jdbc:mysql://localhost:3306/spring_transaction?useSSL=false&characterEncoding=utf-8&autoReconnect=true"; private static String user = "root"; private static String password = "root"; @SuppressWarnings("all") public static void test(TransactionTemplate template, JdbcTemplate jdbcTemplate) { template.execute(new TransactionCallbackWithoutResult() { // doInTransactionWithoutResult无返回值 @SneakyThrows @Override public void doInTransactionWithoutResult(TransactionStatus status) { try { // 插入 jdbcTemplate.execute("insert into person(id, name) values (2, 'jak')"); // 模拟异常 int i = 1 / 0; System.out.println("数据已插入"); } catch (Exception e) { // 标记事务回滚 status.setRollbackOnly(); } } }); } public static void main(String[] args) { // 获取数据源 final DataSource ds = new DriverManagerDataSource(url, user, password); // 编程式事务 final TransactionTemplate template = new TransactionTemplate(); // jdbcTemplate final JdbcTemplate jdbcTemplate = new JdbcTemplate(); // 设置事务管理器 template.setTransactionManager(new DataSourceTransactionManager(ds)); // 配置数据源 jdbcTemplate.setDataSource(ds); test(template, jdbcTemplate); } }
加载全部内容