Spring中常用的是结合AOP的声明式事务管理,也就是不用改变当前已有的代码。而且也比较简单,只需要在Spring的xml中改动4个地方即可。
<?xml version="1.0" encoding="UTF-8"?> <!-- 改动点1:增加事务支持tx --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 使用Spring的数据源替换MyBatis的配置,这里使用Spring提供的JDBC, 这样就不用在MyBatis的xml中来配置数据源了--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!-- 改动点2:配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 事务管理器需要配置数据源,即用户名、密码等数据库连接信息 --> <constructor-arg ref="dataSource"/> </bean> <!-- 改动点3:结合AOP使用事务管理 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 给数据库哪些操作方法配置事务,propagation默认就是REQUIRED,表示如果没有事务,则新建事务, 其他的值可以在网上查一下,所以这里不显式指定propagation也可以 --> <tx:method name="add" propagation="REQUIRED"/> <tx:method name="query" read-only="true"/> </tx:attributes> </tx:advice> <!-- 改动点4:配置事务切入 --> <aop:config> <!-- 配置切入点,这里配置的是mapper包下所有的所有方法 --> <aop:pointcut id="txPointcut" expression="execution(* com.yun.mapper.*.*(..))"/> <!-- 给每个切入点配置事务 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config> </beans>