文章目录
声明式事务管理
1.检查项目中是否已经有Spring-tx的jar包
【注意】一般在导入spring-jdbc的时候默认导入了
如果不放心,可自己导入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
2.修改命名空间
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
3.在beans.xml中配置事务管理
<!--配置事务==================必然拥有-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
以下有所区分:分为注解版本和xml版本
注解版本
开启事务
<!--开启事务===============注解版本-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven>
在需要的service层对应的类上方添加注解@Transactional
@Transactional
void updateSal(int i1, int i2, double sal);
XML版本
配置事务切面
<!--配置事务切面===================XML版本-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.zx.service.impl.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txadvice" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
事务的xml配置
<!--事务的xml配置===================XML版本-->
<tx:advice id="txadvice" transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>