Spring事务是怎么实现的

其他教程   发布日期:2023年09月30日   浏览次数:508

本文小编为大家详细介绍“Spring事务是怎么实现的”,内容详细,步骤清晰,细节处理妥当,希望这篇“Spring事务是怎么实现的”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

    Spring事务如何实现

    1.Spring事务底层是基于数据库事务和AOP机制的

    2.首先对于使用了@Transactional注解的Bean,Spring会创建一个代理对象作为Bean

    3.当调用代理对象的方法时,会先判断该方法上是否加了@Transactional注解

    4.如果加了,那么则利用事务管理器创建一个数据库连接

    5.并且修改数据库连接的autocommit属性为false,禁止此连接的自动提交,这是实现Spring事务非常重要的一步

    6.然后执行当前方法,方法中会执行sql

    7.执行完当前方法后,如果没有出现异常就直接提交事务

    8.如果出现了异常,并且这个异常是需要回滚的就会回滚事务,否则仍然提交事务

    注:

    1.Spring事务的隔离级别对应的就是数据库的隔离级别

    2.Spring事务的传播机制是Spring事务自己实现的,也是Spring事务中最复杂的

    3.Spring事务的传播机制是基于数据库连接来做的,一个数据库连接就是一个事务,如果传播机制配置为需要新开一个事务,那么实际上就是先新建一个数据库连接,在此新数据库连接上执行sql

    Spring事务实现的几种方式

    事务几种实现方式

    (1)编程式事务管理对基于 POJO 的应用来说是唯一选择。我们需要在代码中调用beginTransaction()、commit()、rollback()等事务管理相关的方法,这就是编程式事务管理。

    (2)基于 TransactionProxyFactoryBean的声明式事务管理

    (3)基于 @Transactional 的声明式事务管理

    (4)基于Aspectj AOP配置事务

    编程式事务管理

    1、transactionTemplate

    此种方式是自动的事务管理,无需手动开启、提交、回滚。

    配置事务管理器

    1. <!-- 配置事务管理器 ,封装了所有的事务操作,依赖于连接池 -->
    2. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    3. <property name="dataSource" ref="dataSource"></property>
    4. </bean>

    配置事务模板对象

    1. <!-- 配置事务模板对象 -->
    2. <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    3. <property name="transactionManager" ref="transactionManager"></property>
    4. </bean>

    测试

    1. @Controller
    2. @RequestMapping("/tx")
    3. @RunWith(SpringJUnit4ClassRunner.class)
    4. @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    5. public class TransactionController {
    6. @Resource
    7. public TransactionTemplate transactionTemplate;
    8. @Resource
    9. public DataSource dataSource;
    10. private static JdbcTemplate jdbcTemplate;
    11. private static final String INSERT_SQL = "insert into cc(id) values(?)";
    12. private static final String COUNT_SQL = "select count(*) from cc";
    13. @Test
    14. public void TransactionTemplateTest(){
    15. //获取jdbc核心类对象,进而操作数据库
    16. jdbcTemplate = new JdbcTemplate(dataSource);
    17. //通过注解 获取xml中配置的 事务模板对象
    18. transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    19. //重写execute方法实现事务管理
    20. transactionTemplate.execute(new TransactionCallbackWithoutResult() {
    21. @Override
    22. protected void doInTransactionWithoutResult(TransactionStatus status) {
    23. jdbcTemplate.update(INSERT_SQL, "33"); //字段sd为int型,所以插入肯定失败报异常,自动回滚,代表TransactionTemplate自动管理事务
    24. }
    25. });
    26. int i = jdbcTemplate.queryForInt(COUNT_SQL);
    27. System.out.println("表中记录总数:"+i);
    28. }
    29. }

    2、PlatformTransactionManager

    使用 事务管理器 PlatformTransactionManager 对象,PlatformTransactionManager是DataSourceTransactionManager实现的接口类

    此方式,可手动开启、提交、回滚事务。

    只需要:配置事务管理

    1. <!-- 配置事务管理 ,封装了所有的事务操作,依赖于连接池 -->
    2. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    3. <property name="dataSource" ref="dataSource"></property>
    4. </bean>

    测试

    1. @Controller
    2. @RequestMapping("/tx")
    3. @RunWith(SpringJUnit4ClassRunner.class)
    4. @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    5. public class TransactionController {
    6. @Resource
    7. public PlatformTransactionManager transactionManager;//这里就是将配置数据管理对象注入进来,
    8. @Resource
    9. public DataSource dataSource;
    10. private static JdbcTemplate jdbcTemplate;
    11. private static final String INSERT_SQL = "insert into cc(id) values(?)";
    12. private static final String COUNT_SQL = "select count(*) from cc";
    13. @Test
    14. public void showTransaction(){
    15. //定义使用隔离级别,传播行为
    16. DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    17. def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    18. def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    19. //事务状态类,通过PlatformTransactionManager的getTransaction方法根据事务定义获取;获取事务状态后,Spring根据传播行为来决定如何开启事务
    20. TransactionStatus transaction = transactionManager.getTransaction(def);
    21. jdbcTemplate = new JdbcTemplate(dataSource);
    22. int i = jdbcTemplate.queryForInt(COUNT_SQL);
    23. System.out.println("表中记录总数:"+i);
    24. try {
    25. jdbcTemplate.update(INSERT_SQL,"2");
    26. jdbcTemplate.update(INSERT_SQL,"是否");//出现异常,因为字段为int类型,会报异常,自动回滚
    27. transactionManager.commit(transaction);
    28. }catch (Exception e){
    29. e.printStackTrace();
    30. transactionManager.rollback(transaction);
    31. }
    32. int i1 = jdbcTemplate.queryForInt(COUNT_SQL);
    33. System.out.println("表中记录总数:"+i1);
    34. }
    35. }

    声明式事务管理

    1、基于Aspectj AOP开启事务

    配置事务通知

    1. <!-- 配置事务增强 -->
    2. <tx:advice id="txAdvice" transaction-manager="transactionManager">
    3. <tx:attributes>
    4. <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
    5. </tx:attributes>
    6. </tx:advice>

    配置织入

    1. <!-- aop代理事务。扫描 cn.sys.service 路径下所有的方法 -->
    2. <aop:config>
    3. <!-- 扫描 cn.sys.service 路径下所有的方法,并加入事务处理 -->
    4. <aop:pointcut id="tx" expression="execution(* cn.sys.service.*.*(..))" />
    5. <aop:advisor advice-ref="txAdvice" pointcut-ref="tx" />
    6. </aop:config>

    一个完整的例子

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:aop="http://www.springframework.org/schema/aop"
    5. xmlns:context="http://www.springframework.org/schema/context"
    6. xmlns:tx="http://www.springframework.org/schema/tx"
    7. xsi:schemaLocation="http://www.springframework.org/schema/beans
    8. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    9. http://www.springframework.org/schema/aop
    10. http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    11. http://www.springframework.org/schema/context
    12. http://www.springframework.org/schema/context/spring-context-3.2.xsd
    13. http://www.springframework.org/schema/tx
    14. http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    15. <!-- 创建加载外部Properties文件对象 -->
    16. <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    17. <property name="location" value="classpath:dataBase.properties"></property>
    18. </bean>
    19. <!-- 引入redis属性配置文件 -->
    20. <import resource="classpath:redis-context.xml"/>
    21. <!-- 配置数据库连接资源 -->
    22. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" scope="singleton">
    23. <property name="driverClassName" value="${driver}"></property>
    24. <property name="url" value="${url}"></property>
    25. <property name="username" value="${username}"></property>
    26. <property name="password" value="${password}"></property>
    27. <property name="maxActive" value="${maxActive}"></property>
    28. <property name="maxIdle" value="${maxIdle}"></property>
    29. <property name="minIdle" value="${minIdle}"></property>
    30. <property name="initialSize" value="${initialSize}"></property>
    31. <property name="maxWait" value="${maxWait}"></property>
    32. <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"></property>
    33. <property name="removeAbandoned" value="${removeAbandoned}"></property>
    34. <!-- 配置sql心跳包 -->
    35. <property name= "testWhileIdle" value="true"/>
    36. <property name= "testOnBorrow" value="false"/>
    37. <property name= "testOnReturn" value="false"/>
    38. <property name= "validationQuery" value="select 1"/>
    39. <property name= "timeBetweenEvictionRunsMillis" value="60000"/>
    40. <property name= "numTestsPerEvictionRun" value="${maxActive}"/>
    41. </bean>
    42. <!--创建SQLSessionFactory对象 -->
    43. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    44. <property name="dataSource" ref="dataSource"></property>
    45. <property name="configLocation" value="classpath:MyBatis_config.xml"></property>
    46. </bean>
    47. <!-- 创建MapperScannerConfigurer对象 -->
    48. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    49. <property name="basePackage" value="cn.sys.dao"></property>
    50. </bean>
    51. <!-- 配置扫描器 IOC 注解 -->
    52. <context:component-scan base-package="cn.sys" />
    53. <!-- 配置事务管理 ,封装了所有的事务操作,依赖于连接池 -->
    54. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    55. <property name="dataSource" ref="dataSource"></property>
    56. </bean>
    57. <!-- 配置事务模板对象 -->
    58. <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    59. <property name="transactionManager" ref="transactionManager"></property>
    60. </bean>
    61. <!-- 配置事务增强 -->
    62. <tx:advice id="txAdvice" transaction-manager="transactionManager">
    63. <tx:attributes>
    64. <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
    65. </tx:attributes>
    66. </tx:advice>
    67. <!-- aop代理事务 -->
    68. <aop:config>
    69. <aop:pointcut id="tx" expression="execution(* cn.sys.service.*.*(..))" />
    70. <aop:advisor advice-ref="txAdvice" pointcut-ref="tx" />
    71. </aop:config>
    72. </beans>

    这样就算是给 cn.sys.service下所有的方法加入了事务

    也可以用springboot的配置类方式:

    1. package com.junjie.test;
    2. @Configurationpublic
    3. class TxAnoConfig {
    4. /*事务拦截类型*/
    5. @Bean("txSource")
    6. public TransactionAttributeSource transactionAttributeSource() {
    7. NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
    8. /*只读事务,不做更新操作*/
    9. RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
    10. requiredTx.setTimeout(60);
    11. Map<String, TransactionAttribute> txMap = new HashMap<>();
    12. txMap.put("*", requiredTx);
    13. source.setNameMap(txMap);
    14. return source;
    15. }
    16. /** * 切面拦截规则 参数会自动从容器中注入 */
    17. @Bean
    18. public AspectJExpressionPointcutAdvisor pointcutAdvisor(TransactionInterceptor txInterceptor) {
    19. AspectJExpressionPointcutAdvisor pointcutAdvisor = new AspectJExpressionPointcutAdvisor();
    20. pointcutAdvisor.setAdvice(txInterceptor);
    21. pointcutAdvisor.setExpression("execution (* com.cmb..*Controller.*(..))");
    22. return pointcutAdvisor;
    23. }
    24. /*事务拦截器*/
    25. @Bean("txInterceptor")
    26. TransactionInterceptor getTransactionInterceptor(PlatformTransactionManager tx) {
    27. return new TransactionInterceptor(tx, transactionAttributeSource());
    28. }
    29. }

    2、基于注解的 @Transactional 的声明式事务管理

    1. @Transactional
    2. public int saveRwHist(List list) {
    3. return rwDao.saveRwHist(list);
    4. }

    这个注解的开启需要在spring.xml里加上一个开启注解事务的配置

    以上就是Spring事务是怎么实现的的详细内容,更多关于Spring事务是怎么实现的的资料请关注九品源码其它相关文章!