一、概述
Spring支持两种事务处理机制:
- 编程式事务:把所有事务的代码写在业务中;
- 声明式事务:使用AOP横切进去;一般都会使用声明式事务
要开启 Spring 的事务处理功能,在 Spring 的配置文件中创建一个 DataSourceTransactionManager
对象:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
使用Spring进行事务通知,需要导入约束文件:tx
二、Spring配置事务
1. 导包,导入aspectjweaver包,实现AOP
<!--aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.3</version>
</dependency>
spring-jdbc的包
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
2. 需要配置一个事务管理器,参数需要一个数据源;
数据源
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&
useUnicode=true&characterEncoding=utf-8"/>
</bean>
事务管理器
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
3. 配置声明事务通知
<!--配置声明事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--
name:哪些方法要使用事务【方法】
propagation:配置事务的传播特性
REQUIRED:如果没有事务,就新建一个事务。
-->
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
4. 配置aop织入事务
<!--配置aop织入事务,注意点:需要导入织入的包:aspectj-->
<aop:config>
<!--切入点-->
<aop:pointcut id="txPointCut" expression="execution(* com.kuang.dao.UserDaoImpl.*(..))"/>
<!--通知-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
为什么要配置事务?
事务在项目开发过程中非常重要,涉及到数据的一致性问题,不容马虎!