1.回顾事务
- 事务:一组业务操作ABCD,要么全部成功,要么全部不成功。
- 特性:ACID
原子性:整体
一致性:完成
隔离性:并发
持久性:结果
- 隔离问题:
脏读:一个事务读到另一个事务没有提交的数据
不可重复读:一个事务读到另一个事务已提交的数据(update)
虚读(幻读):一个事务读到另一个事务已提交的数据(insert)
- 隔离级别:
read uncommitted | 读未提交。存在3个问题 |
read committed |
读已提交。解决脏读,存在2个问题 |
repeatable read |
可重复读。解决:脏读、不可重复读,存在1个问题 |
serializable |
串行化。都解决,单事务 |
- mysql 事务操作--简单
ABCD 一个事务
Connection conn = null;
try{
//1 获得连接
conn = ...;
//2 开启事务
conn.setAutoCommit(false);
A
B
C
D
//3 提交事务
conn.commit();
} catche(){
//4 回滚事务
conn.rollback();
}
- mysql 事务操作--Savepoint
需求:AB(必须),CD(可选)
Connection conn = null;
Savepoint savepoint = null; //保存点,记录操作的当前位置,之后可以回滚到指定的位置。(可以回滚一部分)
try{
//1 获得连接
conn = ...;
//2 开启事务
conn.setAutoCommit(false);
A
B
savepoint = conn.setSavepoint();
C
D
//3 提交事务
conn.commit();
} catche(){
if(savepoint != null){ //CD异常
// 回滚到CD之前
conn.rollback(savepoint);
// 提交AB
conn.commit();
} else{ //AB异常
// 回滚AB
conn.rollback();
}
}
2. 事务管理介绍
2.1导入jar包
transaction --> tx
2.2 三个顶级接口
PlatformTransactionManager |
平台事务管理器,spring要管理事务,必须使用事务管理器 进行事务配置时,必须配置事务管理器。 |
TransactionDefinition |
事务详情(事务定义、事务属性),spring用于确定事务具体详情, 例如:隔离级别、是否只读、超时时间 等 进行事务配置时,必须配置详情。spring将配置项封装到该对象实例。 |
TransactionStatus |
事务状态,spring用于记录当前事务运行状态。 例如:是否有保存点,事务是否完成。 spring底层根据状态进行相应操作。 |
2.2.1 PlatformTransactionManager 事务管理器
- 导入jar包:需要时平台事务管理器的实现类
- 常见的事务管理器
DataSourceTransactionManager ,jdbc开发时事务管理器,采用JdbcTemplate
HibernateTransactionManager,hibernate开发时事务管理器,整合hibernate
- api详解
TransactionStatus getTransaction(TransactionDefinition definition) | 事务管理器 通过“事务详情”,获得“事务状态”,从而管理事务 |
void commit(TransactionStatus status) | 根据状态提交 |
void rollback(TransactionStatus status) | 根据状态回滚 |
2.2.2 TransactionStatus
2.22 TransactionDefinition
- 传播行为:在两个业务之间如何共享事务。
required | 必须 | PROPAGATION_REQUIRED | 【默认值】
支持当前事务,A如果有事务,B将使用该事务。 如果A没有事务,B将创建一个新的事务。 |
supports | 支持 | PROPAGATION_SUPPORTS |
支持当前事务,A如果有事务,B将使用该事务。 如果A没有事务,B将以非事务执行。 |
mandatory | 强制 | PROPAGATION_MANDATORY |
支持当前事务,A如果有事务,B将使用该事务。 如果A没有事务,B将抛异常。 |
requires_new | 必须新的 | PROPAGATION_REQUIRES_NEW |
如果A有事务,将A的事务挂起,B创建一个新的事务 如果A没有事务,B创建一个新的事务 |
not_supported | 不支持 | PROPAGATION_NOT_SUPPORTED |
如果A有事务,将A的事务挂起,B将以非事务执行 如果A没有事务,B将以非事务执行 |
never | 从不 | PROPAGATION_NEVER |
如果A有事务,B将抛异常 如果A没有事务,B将以非事务执行 |
nested | 嵌套 | PROPAGATION_NESTED | A和B底层采用保存点机制,形成嵌套事务。 |
掌握:PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW、PROPAGATION_NESTED
2.3 案例:转账
2.3.1 搭建环境
2.3.1.1 创建表
create database spring;
use spring;
create table account(
id int primary key auto_increment,
username varchar(50),
money int
);
insert into account(username,money) values('jack','10000');
insert into account(username,money) values('rose','10000');
2.3.1.2 导入jar包
核心:4+1 |
aop : 4 (aop联盟、spring aop、aspectj规范、spring aspect) |
数据库:2 (jdbc/tx) |
驱动:mysql |
连接池:c3p0 |
2.3.1.3 dao 层
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
@Override
public void out(String outer, Integer money) {
this.getJdbcTemplate().update("update account set money = money - ? where username = ?", money,outer);
}
@Override
public void in(String inner, Integer money) {
this.getJdbcTemplate().update("update account set money = money + ? where username = ?", money,inner);
}
}
2.3.1.3 service层
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String outer, String inner, Integer money) {
accountDao.out(outer, money);
//断电
// int i = 1/0;
accountDao.in(inner, money);
}
}
2.3.1.4 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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- datasource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_tx"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- dao -->
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- service -->
<bean id="accountService" class="com.service.impl.AccountServcieImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
</beans>
2.3.1.5 测试
@Test
public void demo01(){
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
AccountService accountService = (AccountService) applicationContext.getBean("accountService");
accountService.transfer("jack", "rose", 1000);
}
2.3.2 手动管理事务(了解)
- spring底层使用 TransactionTemplate 事务模板进行操作
- 操作
1.service 需要获得 TransactionTemplate
2.spring 配置模板,并注入给service
3.模板需要注入事务管理器
4.配置事务管理器:DataSourceTransactionManager ,需要注入DataSource
2.3.2.1 DAO 类
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class AccountDaoImple extends JdbcDaoSupport implements AccountDao {
@Override
public void out(String outer, int money) {
this.getJdbcTemplate().update("update account set money = money - ? where name = ?",money,outer);
}
@Override
public void in(String inner, int money) {
this.getJdbcTemplate().update("update account set money = money + ? where name = ?", money,inner);
}
}
2.3.2 .2修改service
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
//需要spring注入模板
private TransactionTemplate transactionTemplate;
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
@Override
public void transfer(final String outer,final String inner,final Integer money) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus arg0) {
accountDao.out(outer, money);
//断电
// int i = 1/0;
accountDao.in(inner, money);
}
});
}
}
2.3.2.3 修改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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 创建数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_tx"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置dao -->
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置service -->
<bean id="accountService" class="com.service.impl.AccountServcieImpl">
<property name="accountDao" ref="accountDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean>
<!-- 创建模板 -->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="txManager"></property>
</bean>
<!-- 配置事务管理器 ,管理器需要事务,事务从Connection获得,连接从连接池DataSource获得 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
2.3.2.4 测试
package com.Test;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.AccountServcie;
public class TestApp {
@Test
public void Demo() {
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
AccountServcie accountServcie = (AccountServcie) applicationContext.getBean("accountService");
accountServcie.transfer("rose", "jack", 1000);
}
}
2.3.3工厂bean 生成代理:半自动
- spring提供 管理事务的代理工厂bean TransactionProxyFactoryBean
1.getBean() 获得代理对象
2.spring 配置一个代理
2.3.3.1 DAO 类
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class AccountDaoImple extends JdbcDaoSupport implements AccountDao {
@Override
public void out(String outer, int money) {
this.getJdbcTemplate().update("update account set money = money - ? where name = ?",money,outer);
}
@Override
public void in(String inner, int money) {
this.getJdbcTemplate().update("update account set money = money + ? where name = ?", money,inner);
}
}
2.3.3.2 Service 类
package com.service.impl;
import com.dao.AccountDao;
import com.service.AccountServcie;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String outer, String inner, int money) {
accountDao.out(outer, money);
int i = 1 / 0;
accountDao.in(inner, money);
}
}
2.3.3.3 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 创建数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_tx"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>c
<!-- 配置dao -->
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置service -->
<bean id="accountService" class="com.service.impl.AccountServcieImpl">
<property name="accountDao" ref="accountDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 4 service 代理对象
4.1 proxyInterfaces 接口
4.2 target 目标类
4.3 transactionManager 事务管理器
4.4 transactionAttributes 事务属性(事务详情)
prop.key :确定哪些方法使用当前事务配置
prop.text:用于配置事务详情
格式:PROPAGATION,ISOLATION,readOnly,-Exception,+Exception
传播行为 隔离级别 是否只读 异常回滚 异常提交
例如:
<prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop> 默认传播行为,和隔离级别
<prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop> 只读
<prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,+java.lang.ArithmeticException</prop> 有异常扔提交 -->
<bean id="proxyAccountService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="proxyInterfaces" value="cn.lm.tx02.AccountService"></property>
<property name="target" ref="accountServiceImplId"></property>
<property name="transactionManager" ref="txManager"></property>
<property name="transactionAttributes">
<props>
<prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop>
</props>
</property>
</bean>
</beans>
2.3.3.4 测试
package com.Test;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.AccountServcie;
public class TestApp {
@Test
public void Demo() {
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
AccountServcie accountServcie = (AccountServcie) applicationContext.getBean("proxyAccountService");
accountServcie.transfer("rose", "jack", 1000);
}
}
2.3.4 AOP 配置基于xml【掌握】
- 在spring xml 配置aop 自动生成代理,进行事务的管理
1.配置管理器
2.配置事务详情
3.配置aop
2.3.4 .1 DAO
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class AccountDaoImple extends JdbcDaoSupport implements AccountDao {
@Override
public void out(String outer, int money) {
this.getJdbcTemplate().update("update account set money = money - ? where name = ?",money,outer);
}
@Override
public void in(String inner, int money) {
this.getJdbcTemplate().update("update account set money = money + ? where name = ?", money,inner);
}
}
2.3.4 .2 Service
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String outer, String inner, int money) {
accountDao.out(outer, money);
int i = 1 / 0;
accountDao.in(inner, money);
}
}
2.3.4 .3 Service 配置文件
<?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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 创建数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_tx"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置dao -->
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置service -->
<bean id="accountService" class="com.service.impl.AccountServcieImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置 事务详情(事务通知) , 在aop筛选基础上,对ABC三个确定使用什么样的事务。例如:AC读写、B只读 等
<tx:attributes> 用于配置事务详情(属性属性)
<tx:method name=""/> 详情具体配置
propagation 传播行为 , REQUIRED:必须;REQUIRES_NEW:必须是新的
isolation 隔离级别 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!-- AOP编程,目标类有ABCD(4个连接点),切入点表达式 确定增强的连接器,从而获得切入点:ABC -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.service..*.*(..))"/>
</aop:config>
</beans>
2.3.4 .4 测试
package com.Test;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.AccountServcie;
public class TestApp {
@Test
public void Demo() {
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
AccountServcie accountServcie = (AccountServcie) applicationContext.getBean("accountService");
accountServcie.transfer("rose", "jack", 1000);
}
}
2.3.5 AOP配置基于注解【掌握】
- 配置事务管理器,将并事务管理器交予spring
- 在目标类或目标方法添加注解即可 @Transactional
2.3.5.1 Service 层
package com.service.impl;
import org.springframework.transaction.annotation.Transactional;
import com.dao.AccountDao;
import com.service.AccountServcie;
@Transactional()
public class AccountServcieImpl implements AccountServcie{
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String outer, String inner, Integer money) {
accountDao.in(inner, money);
// 断点
//int i = 1/0;
accountDao.out(outer, money);
}
}
2.3.5.2 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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 1 datasource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_tx"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 2 dao -->
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3 service -->
<bean id="accountService" class="com.service.impl.AccountServcieImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 4 事务管理 -->
<!-- 4.1 事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 4.2 将管理器交予spring
* transaction-manager 配置事务管理器
* proxy-target-class
true : 底层强制使用cglib 代理
-->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
2.3.5.3 事物配置详情
@Transactional(propagation=Propagation.REQUIRED , isolation = Isolation.DEFAULT)
public class AccountServiceImpl implements AccountService {