Spring的事务控制
一:编程式事务控制相关对象
- PlatformTransactionManager
- jdbc/mybatis:DataSourceTransactionManager
- hibernate:HibernateTransactionManager
- TransactionDefinition
- TransactionStatus
1.1:PlatformTransactionManager接口
- 概述
PlatformTransactionManager接口
是spring的事务管理器,它声明了一些标准!比如获取事务的状态信息,提交事务,回滚事务方法,不同的 Dao层技术则有不同的实现类,比如jdbc/mybatis对应的实现类是DataSourceTransactionManager
- 方法
public interface PlatformTransactionManager {
TransactionStatus getTransaction(@Nullable TransactionDefinition var1) throws TransactionException; //获取事务的状态信息
void commit(TransactionStatus var1) throws TransactionException; //提交事务
void rollback(TransactionStatus var1) throws TransactionException; //回滚事务
}
1.2:TransactionDefinition接口
- 概述
TransactionDefinition是事务的定义信息对象,常用的方法如下
- 方法
public interface TransactionDefinition{
int getPropagationBehavior(); //获取事务的传播行为
int getIsolationLevel(); //获取事务的隔离级别
int getTimeout(); //获取超时时间
boolean isReadOnly(); //判断是否只读
}
- 事务的隔离级别
设置隔离级别可以解决事务并发产生的问题,如
脏读
,不可重复读
,幻读(虚读)
public enum Isolation {
DEFAULT(-1),
READ_UNCOMMITTED(1), //读未提交
READ_COMMITTED(2), //读已提交
REPEATABLE_READ(4), //可重复读
SERIALIZABLE(8); //串行化
}
- 事务的传播行为
传播行为的作用:主要解决业务方法在调业务方法时他们之间事务统一性的问题
1.REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。(默认值)
2.SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
3.MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
4.REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
5.NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
6.NEVER:以非事务方式运行,如果当前存在事务,抛出异常
7.NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作
8.超时时间:默认值是-1,没有超时限制。如果有,以秒为单位进行设置
9.是否只读:建议查询时设置为只读
注:1,2点比较常用
- 例子
public void a(){
b()
}
public void b(){
}
1、a业务方法包含b业务方法,如果传播行为设置的是
REQUIRED
,那是什么意思呢?,参照上面的说法套
站在被包含业务方法(b)的角度:
如果当前a业务方法中没有事务,那么b业务方法就新建一个事务
如果当前a业务方法中有事务, 那么b业务方法就加入进去
注:思想, 没有就创建,有就使用(感觉有点像懒汉式的单例 哈哈哈)
private Object obj = null;
public static Object getInstance(){
if(obj == null){
obj = new Object();
}
return obj;
}
2、a业务方法包含b业务方法,如果传播行为设置的是
SUPPORTS
那是什么意思呢?参照上面的说法套
站在被调用的业务方法(b)的角度:
如果当前a业务方法中有事务, 那么b业务方法就加入进去
如果当前a业务方法中没有事务,那么b业务方法就以非事务的方式执行!
注:思想,有就用,没有就不用
1.3:TransactionStatus接口
- 概述
TransactionStatus 接口提供的是事务具体的运行状态
- 方法
public interface TransactionStatus extends SavepointManager, Flushable {
boolean isNewTransaction(); //是否是新事务
boolean hasSavepoint(); //是否存储回滚点
void setRollbackOnly();
boolean isRollbackOnly(); //事务是否回滚
void flush();
boolean isCompleted(); //事务是否完成
}
二:基于 XML的声明式事务控制
2.1:搭建一个转账业务的环境,为后续测试事务做准备!
分析:
转账业务:
zs: 2000
ls: 2000
zs -> ls 转1000
Service层: 业务方法:transfer(zs,ls,1000)
Dao层:对应数据库的操作:
减钱: update account set money=money-1000 where name = ?
加钱: update account set money=money+1000 where name = ?
-
结构如下
-
1、pom.xml中依赖的jar
<dependencies>
<!--
使用spring开发的话必须导入spring-context基础包
注: 加载spring核心配置文件需要它, 一些@@Component注解也是需要导入它的!
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--aop: spring-aop(包含在spring-context中了)和aspectj-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!--mysql驱动和c3p0数据库连接池-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--使用lombok简化实体类的开发-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<!--spring集成junit测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
- 2、spring中配置jdbcTemplate
jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&charaterEncoding=utf-8&useSSL=false
jdbc.user=root
jdbc.password=123456
applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--1.开启注解扫描-->
<context:component-scan base-package="com.wzj"></context:component-scan>
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
- 3、数据库中的表和实体类
1.建表语句
CREATE TABLE `account` (
`name` varchar(20) NOT NULL,
`money` decimal(10,0) NOT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.数据如下:
| name | money |
| wzj | 100 |
| dyt | 100 |
@Data
public class Account {
private String name;
private double money;
}
- 3、三层:Controller,Service,Dao
Controller(web层)
依赖Service层(业务层)
Service(业务层)
依赖Dao层
- Dao接口和实现类
public interface AccountDao {
//给谁加钱
void increase(String name, double money);
//给谁减钱
void reduce(String name, double money);
}
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void increase(String name, double money) {
jdbcTemplate.update("update account set money=money+? where name=?",money,name);
}
@Override
public void reduce(String name, double money) {
jdbcTemplate.update("update account set money=money-? where name=?",money,name);
}
}
- Service接口和实现类
public interface AccountService {
/**
* 转账业务
* @param payer 付款人
* @param payee 收款人
* @param money 转账金额
*/
void transfer(String payer, String payee, double money);
}
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public void transfer(String payer, String payee, double money) {
//1.先减去付款人的金额
accountDao.reduce(payer,money);
// int i = 10/0;
//2.再加上收款人的金额
accountDao.increase(payee,money);
}
}
- web层
public class AccountController {
public static void main(String[] args) {
//模拟Controller层, 调用Service层的转账方法!
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = (AccountService) applicationContext.getBean("accountService");
accountService.transfer("dyt","wzj",100);
}
}
2.2:基于 XML 的声明式事务控制的实现
- 在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:context="http://www.springframework.org/schema/context"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--1.开启注解扫描-->
<context:component-scan base-package="com.wzj"></context:component-scan>
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--3.事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2.通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="true"></tx:method>-->
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>
</tx:attributes>
</tx:advice>
<!--
配置AOP事务的切面, 注:事务的aop切面选advisor,其他的选aspect
1.切面 = 通知/增强 + 切点
-->
<aop:config>
<!--<aop:pointcut id="myPointcut" expression=""/>-->
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.wzj.service.impl.AccountServiceImpl.*(..))"></aop:advisor>
</aop:config>
</beans>
配置思路:
1.先配置切面,因为切面 = 通知/增强 + 切点(把依赖的东西先给引出来,然后顺藤摸瓜)
注:这里的切面是<aop:advisor>
而不是<aop:aspect>
2.然后根据
advice-ref
属性知道需要配置通知,根据pointcut
属性知道需要配置切点表达式3.使用
<tx:advice>
来配置通知,根据transaction-manager
属性知道需要配置事务管理器4.由于使用的Dao层技术是jdbc,所以事务管理器接口对应的实现是
DataSourceTransactionManager
5.由于事务是由连接
connection
,来开启,提交,回滚的,而连接存在于数据源中,所以事务需要引用数据源
注:此时就已经对com.wzj.service.impl.AccountServiceImpl类中的
transfer
方法启动了事务这时就算转账的时候出现了运行时异常,金额也不会乱套 !
<tx:method>
代表切点方法的事务参数的配置
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>
name
:切点方法名称,isolation
:事务的隔离级别,propogation
:事务的传播行为,timeout
:超时时间,read-only
:是否只读(一般查询操作才设置为true,更新操作设置为false)
- 总结
1.注意事项
声明式事务控制明确事项:
谁是切点?需要使用AOP事务控制的业务方法
谁是通知?事务通知/增强
配置切面?其实就是在配置将通知应用于切点的一个过程
2.大概步骤:
平台事务管理器配置
事务通知的配置
事务aop织入的配置
2.3:基于注解的声明式事务控制的实现
注:掌握了xml的配置方式,那么使用注解的方式,更加简单
- 步骤
1.将在xml中配置Aop事务切面的形式,变成在类中配置注解的形式
2.使用注解的方式一定要在spring配置中开启事务注解驱动<tx:annotation-driven/>
- 1、将在xml中配置Aop事务切面的形式,变成在类中配置注解的形式
<!--通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!– <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="true"></tx:method>–>
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"
</tx:attributes>
</tx:advice>
<!--AOP配置:aop事务切面-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.wzj.service.impl.AccountServiceImpl.*(..))"></aop:advisor>
</aop:config>
将上面这段xml变成注解形式
@Service("accountService")
//@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, timeout = -1, readOnly = false)
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, timeout = -1, readOnly = false)
public void transfer(String payer, String payee, double money) {
//1.先减去付款人的金额
accountDao.reduce(payer,money);
int i = 10/0;
//2.再加上收款人的金额
accountDao.increase(payee,money);
}
}
注:为什么不需要写切点了呢?因为
@Transactional
注解就打在该方法上,肯定知道切点就是该方法,至于事务参数的配置,有需要还是可以进行配置的!
- 注意点
1.加上了@Transactional注解其实就是为该业务方法(切点)进行的事务通知/增强,注解里面的参数其实是配置事务参数的,如隔离级别,传播行为,超时时间,是否只读等, 它们都是有默认值的!,所以只是在需要改变的时候才去配置
2.@Transactional注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置。,如果类上使用了@Transactional注解,类中的某个方法也打上了@Transactional,那么以方法上的注解为主,就近原则!
3.一般自定义bean,如xxxController,xxxService都用@Compoent等注解去修饰,但是一些第三方的类(JdbcTemplate,DataSourceTransactionManager)无法使用
@Component等注解去修饰,那么一般是配置在spring的核心配置文件中,要么使用@Bean的方式!
4.最后再次提醒,使用基于注解的声明式事务控制的,一定要加上事务注解驱动<tx:annotation-driven>
最后:来自虽然帅,但是菜的cxy