1.概念
- 事务就是用户定义的一系列执行SQL语句的操作, 这些操作要么完全地执行,要么完全地都不执行, 它是一个不可分割的工作执行单元
- 一个使用Mybatis-Spring的主要原因是它允许Mybatis参与到Spring的事务管理中,而不是给Mybatis创建一个新的专用事务管理器
2.步骤
2.1.spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--Spring整合Mybatis,省略了Mybatis的核心配置文件,转而在Spring的配置文件中配置Mybatis-->
<!--datasource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/user?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- <property name="configLocation" value="classpath:mybatis-config.xml"/>-->
<property name="mapperLocations" value="classpath:com/sun/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的sqlSession,这个是spring提供的-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!--我们只能使用构造器注入,因为没有set方法-->
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<bean id="UserMapperImpl" class="com.sun.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
</beans>
2.2.配置声明式事务
<!--配置声明式事务-->
<bean id="transationManage" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
2.3.用AOP的方式实现事务
<!--结合AOP实现事务的织入-->
<!--第一步:配置事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transationManage">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
2.4.配置事务切入
<aop:config>
<aop:pointcut id="PointCut" expression="execution(* com.sun.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="PointCut"/>
</aop:config>