事务回顾
参见【数据库事务了解一下】。
Spring 事务管理 API
PlatformTransactionManager
平台事务管理器接口,是 Spring 用于管理事务真正的对象。
DataSourceTransactionManager
:底层使用 JDBC 管理事务。HibernateTransactionManager
:底层使用Hibernate
管理事务。
TransactionDefinition
事务定义信息,用于定义事务的相关的信息,隔离级别、超时信息、传播行为、是否只读。
TransactionStatus
事务的状态,用于记录在事务管理过程中,事务的状态的对象。
上述API之间的关系:
Spring 进行事务管理的时候,首先平台事务管理器根据事务定义信息进行事务的管理,在事务管理过程中,产生各种状态,将这些状态的信息记录到事务状态的对象中。
事务的传播行为
Spring 中提供了七种事务的传播行为,可分为如下三类:
保证多个操作在同一个事务中
PROPAGATION_REQUIRED
:默认值,如果 A 中有事务,使用 A 中的事务,如果 A 没有,创建一个新的事务,将操作包含进来;PROPAGATION_SUPPORTS
:支持事务,如果 A 中有事务,使用 A 中的事务。如果 A 没有事务,不使用事务。PROPAGATION_MANDATORY
:如果 A 中有事务,使用 A 中的事务。如果 A 没有事务,抛出异常。
保证多个操作不在同一个事务中
PROPAGATION_REQUIRES_NEW
:如果 A 中有事务,将 A 的事务挂起(暂停),创建新事务,只包含自身操作。如果 A 中没有事务,创建一个新事务,包含自身操作。PROPAGATION_NOT_SUPPORTED
:如果 A 中有事务,将 A 的事务挂起。不使用事务管理。PROPAGATION_NEVER
:如果 A 中有事务,报异常。
嵌套式事务
PROPAGATION_NESTED
:嵌套事务,如果 A 中有事务,按照 A 的事务执行,执行完成后,设置一个保存点,执行 B 中的操作,如果没有异常,执行通过,如果有异常,可以选择回滚到最初始位置,也可以回滚到保存点。
Spring 事务管理案例
准备
创建 account
表并初始化如下数据:
准备下面代码模拟一个转账场景:
// com.zze.dao.AccountDao
package com.zze.dao;
public interface AccountDao {
/**
* 转出
* @param username 转出账户的用户名
* @param money 转出金额
*/
void outMoney(String username,Double money);
/**
* 转入
* @param username 转入账户的用户名
* @param money 转入金额
*/
void inMoney(String username, Double money);
}
// com.zze.dao.impl.AccountDaoImpl
package com.zze.dao.impl;
import com.zze.dao.AccountDao;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
@Override
public void outMoney(String username, Double money) {
this.getJdbcTemplate().update("update account set money=money-? where username=?", money, username);
}
@Override
public void inMoney(String username, Double money) {
this.getJdbcTemplate().update("update account set money=money+? where username=?", money, username);
}
}
// com.zze.service.AccountService
package com.zze.service;
public interface AccountService {
/**
* 转账
* @param usernameFrom 转账来源账户
* @param usernameTo 转账目标账户
* @param money 转账金额
*/
void transfer(String usernameFrom,String usernameTo,Double money);
}
// com.zze.service.impl.AccountServiceImpl
package com.zze.service.impl;
import com.zze.dao.AccountDao;
import com.zze.service.AccountService;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String usernameFrom, String usernameTo, Double money) {
accountDao.outMoney(usernameFrom, money);
accountDao.inMoney(usernameTo,money);
}
}
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.username=root
jdbc.password=root
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
-->
<bean name="accountDao" class="com.zze.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"/>
<!--<property name="jdbcTemplate" ref="jdbcTemplate"/>-->
</bean>
<bean name="accountService" class="com.zze.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
</beans>
import com.zze.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
@Resource(name = "accountService")
private AccountService accountService;
@Test
public void test(){
// zhangsan 给 lisi 转账 100
accountService.transfer("zhangsan","lisi",100d);
}
}
编程式事务管理
1、修改配置:
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置 C3p0 连接池-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置事务管理器-->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务的管理的模板类-->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"/>
</bean>
<bean name="accountDao" class="com.zze.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="accountService" class="com.zze.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
<!--注入事务管理模板-->
<property name="transactionTemplate" ref="transactionTemplate"/>
</bean>
</beans>
2、修改代码模拟异常并使用事务:
// com.zze.service.impl.AccountServiceImpl
package com.zze.service.impl;
import com.zze.dao.AccountDao;
import com.zze.service.AccountService;
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;
private TransactionTemplate transactionTemplate;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
@Override
public void transfer(String usernameFrom, String usernameTo, Double money) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
accountDao.outMoney(usernameFrom, money);
// 模拟过程中异常
int i = 1 / 0;
accountDao.inMoney(usernameTo, money);
}
});
}
}
3、测试:
import com.zze.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
@Resource(name = "accountService")
private AccountService accountService;
@Test
public void test(){
// zhangsan 给 lisi 转账 100
accountService.transfer("zhangsan","lisi",100d);
// 此时表数据将不会发生变化
}
}
XML 声明式事务管理
1、修改配置:
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置 C3p0 连接池-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置事务管理器-->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务的通知/增强-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--事务管理规则-->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true"/>
<!--
name : 匹配方法名
read-only : 为 true 时表示只做只读操作
propagation : 事务的传播行为
timeout : 事务过期时间,为 -1 时不会过期
isolation : 事务的隔离级别
-->
<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" timeout="-1"/>
</tx:attributes>
</tx:advice>
<!--AOP 配置-->
<aop:config>
<aop:pointcut id="pc_account" expression="execution(* com.zze.service.AccountService.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc_account"/>
</aop:config>
<bean name="accountDao" class="com.zze.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="accountService" class="com.zze.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
</beans>
2、修改代码模拟异常:
// com.zze.service.impl.AccountServiceImpl
package com.zze.service.impl;
import com.zze.dao.AccountDao;
import com.zze.service.AccountService;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String usernameFrom, String usernameTo, Double money) {
accountDao.outMoney(usernameFrom, money);
// 模拟过程中异常
int i = 1 / 0;
accountDao.inMoney(usernameTo, money);
}
}
3、测试:
import com.zze.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
@Resource(name = "accountService")
private AccountService accountService;
@Test
public void test(){
// zhangsan 给 lisi 转账 100
accountService.transfer("zhangsan","lisi",100d);
// 此时表数据将不会发生变化
}
}
注解声明式事务管理
1、修改配置:
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置 C3p0 连接池-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置事务管理器-->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启注解事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean name="accountDao" class="com.zze.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="accountService" class="com.zze.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
</beans>
2、修改代码模拟异常并添加事务注解:
// com.zze.service.impl.AccountServiceImpl
package com.zze.service.impl;
import com.zze.dao.AccountDao;
import com.zze.service.AccountService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 业务类上添加注解使用事务
@Transactional(isolation=Isolation.DEFAULT,propagation = Propagation.REQUIRED)
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String usernameFrom, String usernameTo, Double money) {
accountDao.outMoney(usernameFrom, money);
// 模拟过程中异常
int i = 1 / 0;
accountDao.inMoney(usernameTo, money);
}
}
3、测试:
import com.zze.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
@Resource(name = "accountService")
private AccountService accountService;
@Test
public void test(){
// zhangsan 给 lisi 转账 100
accountService.transfer("zhangsan","lisi",100d);
// 此时表数据将不会发生变化
}
}
评论区