文章目录
Spring 中的事务控制
1. Spring 事务控制我们需要明确的
- Jave EE 体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计业务层的事务处理解决方案。
- Spring 框架为我们提供了一组事务控制的接口。这组接口主要在 spring-tx 中。
- Spring 的事务控制都是基于 AOP 的,它即可以使用编程的方式实现,也可以使用配置的方式实现。我们学习的重点是使用配置的方式实现。
2. Spring 中事务控制的 API 介绍
1. PlatformTransactionManager
此接口是 Spring 的事务管理器,它里面提供了我们常用的操作事务的方法,
TransactionStatus getTransaction(TransactionDefinition definition)
- 获取事务状态信息
void commit(TransactionStatus status)
- 提交事务
void rollback
- 回滚事务
在使用事务管理时,一定要记得需要创建一个真正的管理事务的对象
org.springframework.jdbc.datasource.DataSourceTransactionManager
使用Spring JDBC 或者 mybatis 进行持久化数据时使用
org.springframework.orm.hibernate5.HibernateTransactionManager
使用 Hibernate 版本进行持久化数据时使用。
2. TransactionDefinition
它是事务的定义信息对象,里面有如下方法:
-
String getName()
- 获取事务对象名称
-
int getIsolationLevel()
- 获取事务隔离级
-
int getPropagationBehavior()
- 获取事务传播行为
-
int getTimeout()
- 获取事务超时时间
-
boolean isReadOnly()
- 获取事务是否只读
2.1 事务的隔离级别
事务隔离级反映事务提交并发访问时的处理态度
- ISOLATION_DEFAULT
- 默认级别,归属下列某一种
- ISOLATION_READ_UNCOMMITTED
- 可读取未提交数据
- ISOLATION_READ_COMMITTED
- 只能读取已提交数据,解决脏读问题( Oracle 默认级别)
- ISOLATION_REPEATABLE_READ
- 是否读取其他事务提交修改后的数据,解决不可重复读问题(mysql 默认级别)
- ISOLATION_SERIALIZABLE
- 是否读取其他事务提交添加后的数据,解决幻影读问题
2.2 事务的传播行为
- REQUIRED: - 增删改
- 如果当前没有事务,就新建一个事务,如果已经存在一个事务中,就加入到这个事务中。一般的选择(默认值)。
- SUPPORTS: - 查询
- 支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)。
- MANDATORY:
- 使用当前的事务,如果当前没有事务,就抛出异常。
- REQUERS_NEW:
- 新建事务,如果当前在事务中,把当前事务挂起。
- NOT_SUPPORTED:
- 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
- NEVER:
- 以非事务方式运行,如果当前存在事务,就抛出异常。
2.3 超时时间
默认值是 -1,没有超时限制。如果有,以秒为单位进行设置。
2.4 是否是只读事务
建议查询时设置为只读。
3. TransactionStatus
此接口提供的是事务具体的运行状态,方法介绍如下:
TransactionStatus 接口描述了某个时间点上事务对象的状态信息,包含有6个具体的操作:
- void flush()
- 刷新事务
- boolean hasSavepoint()
- 获取是否是存在存储点
- boolean isCompleted()
- 获取事务是否完成
- boolean isNewTranscation()
- 获取事务是否为新的事务
- boolean isRollbackOnly()
- 获取事务是否回滚
- void setRollbackOnly()
- 设置事务回滚
3. 基于 XML 的声明式事务控制(配置方式)
1. 前提条件
-
首先,创建一个 maven 项目
-
接下来,创建实体类:
package com.spring.domain; public class Account { private Integer id; private String name; private Float money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getMoney() { return money; } public void setMoney(Float money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
-
然后,创建持久层的 dao 类和其实现类:
package com.spring.dao; import com.spring.domain.Account; public interface IAccountDao { /** * 根据 id 查询账户信息 * @param id * @return */ Account findAccountById(Integer id); /** * 根据 name 查询账户信息 * @param accountName * @return */ Account findAccountByName(String accountName); /** * 根据账户 * @param account */ void updateAccount(Account account); }
package com.spring.dao.impl; import com.spring.dao.IAccountDao; import com.spring.domain.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository("accountDao") public class AccountDaoImpl implements IAccountDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public Account findAccountById(Integer accountId) { List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId); return accounts.isEmpty()?null:accounts.get(0); } @Override public Account findAccountByName(String accountName) { List<Account> accounts = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), accountName); if(accounts.size() > 1) { throw new RuntimeException("数据异常,用户名不唯一"); } if(accounts.isEmpty()) { return null; } else { return accounts.get(0); } } @Override public void updateAccount(Account account) { jdbcTemplate.update("update account set name = ?, money = ? where id = ?", account.getName(), account.getMoney(), account.getId()); } }
-
创建业务层 dao 类和其实现类:
package com.spring.service; import com.spring.domain.Account; /** * 账户的业务层接口 */ public interface IAccountService { /** * 根据 id 查询账户信息 * @param accountId * @return */ Account findAccountById(Integer accountId); /** * 根据 name 查询用户信息 * @param accountName * @return */ Account findAccountByName(String accountName); /** * 转账 * @param sourceName * @param targetName * @param money */ void transfer(String sourceName, String targetName, Float money); /** * 更新 * @param account */ void updateAccount(Account account); }
package com.spring.service.impl; import com.spring.dao.IAccountDao; import com.spring.domain.Account; import com.spring.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("accountService") public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; @Override public Account findAccountById(Integer accountId) { return accountDao.findAccountById(accountId); } @Override public Account findAccountByName(String accountName) { return accountDao.findAccountByName(accountName); } @Override public void transfer(String sourceName, String targetName, Float money) { Account source = accountDao.findAccountByName(sourceName); Account target = accountDao.findAccountByName(targetName); source.setMoney(source.getMoney() - money); target.setMoney(target.getMoney() + money); accountDao.updateAccount(source); accountDao.updateAccount(target); } @Override public void updateAccount(Account account) { accountDao.updateAccount(account); } }
2. 使用 xml 配置声明式事务控制
配置声明式事物控制一共有五个步骤:
-
配置事务管理器:
<!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
-
配置事务的通知:
<!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> </tx:advice>
配置事物的通知是在事务的通知
tx:advice
标签的内部。此时,我们需要导入事务的约束 tx 名称空间和约束,同时也需要 aop 的:
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://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 https://www.springframework.org/schema/tx/spring-tx.xsd">
使用
tx:advice
标签配置事务通知- 属性:
- id:给事务通知起一个唯一标志
- transaction-manager:给事务通知提供一个事务管理器引用
- 属性:
-
配置 aop 中的通用切入点表达式:
<aop:config> <!-- 配置切入点表达式 --> <aop:pointcut id="pt1" expression="execution(* com.spring.service.impl.*.*(..))"/> </aop:config>
这里的切入点表达式是在
aop:config
中配置。 -
建立事务通知和切入点表达式的对应关系
<aop:config> <!-- 配置切入点表达式 --> <aop:pointcut id="pt1" expression="execution(* com.spring.service.impl.*.*(..))"/> <!-- 建立切入点表达式和事务通知的对应关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor> </aop:config>
-
配置事务的属性:
这些属性是在事务的通知
tx:advice
标签的内部。- isolation:它适用于指定事务的隔离级别,默认值是 DEFAULT, 表示使用数据库的默认隔离级别。
- propagation:用于指定事务的传播行为,默认值是 REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
- read-only:用于指定事务是否只读,只有查询方法才能设置为 true 只读,默认为 false 表示读写。
- no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚;产生其他异常时,事务回滚。没有默认值,表示任何异常都回滚。
- rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示任何异常都回滚。
- timeout:用于指定事务的超时时间,默认值是 -1,表示永不超时。如果指定了数值,以秒为单位。
<!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 配置事务的属性 --> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="false"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method> </tx:attributes> </tx:advice>
-
以下是完整的配置文件:
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://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 https://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="com.spring"></context:component-scan> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg ref="dataSource"></constructor-arg> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/spring?serverTimezone=Asia/Shanghai"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 配置事务的属性 --> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="false"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method> </tx:attributes> </tx:advice> <aop:config> <!-- 配置切入点表达式 --> <aop:pointcut id="pt1" expression="execution(* com.spring.service.impl.*.*(..))"/> <!-- 建立切入点表达式和事务通知的对应关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor> </aop:config> </beans>
4. Spring 基于注解的声明式事务控制
-
配置事务管理器
<!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
-
开启 Spring 对注解事务的支持:
<!-- 开启 Spring 对注解事务的支持 --> <tx:annotation-driven></tx:annotation-driven>
-
在需要事务支持的地方使用 @Transactional 注解:
package com.spring.service.impl; import com.spring.dao.IAccountDao; import com.spring.domain.Account; import com.spring.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service("accountService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; @Override public Account findAccountById(Integer accountId) { return accountDao.findAccountById(accountId); } @Override public Account findAccountByName(String accountName) { return accountDao.findAccountByName(accountName); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void transfer(String sourceName, String targetName, Float money) { Account source = accountDao.findAccountByName(sourceName); Account target = accountDao.findAccountByName(targetName); source.setMoney(source.getMoney() - money); target.setMoney(target.getMoney() + money); int i = 1/0; accountDao.updateAccount(source); accountDao.updateAccount(target); } @Override public void updateAccount(Account account) { accountDao.updateAccount(account); } }
在 Transactional 注解中,可以进行事务属性的配置。
5. Spring 基于纯注解的声明式事务控制
第一步:
由于是使用纯注解的声明式事务控制,所以,需要创建一个配置类。在源包下创建 config 包并创建 SpringConfiguration 类:
为了使 SpringConfiguration 类成为一个 Spring 的配置类,在类上增加注解:
package com.spring.config;
import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
/**
* Spring 的配置类,相当于 bean.xml
*/
@Configuration
public class SpringConfiguration {
}
在之前使用配置文件和注解相结合的方式进行配置的基础上,首先来看一下配置文件:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://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
https://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.spring"></context:component-scan>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring?serverTimezone=Asia/Shanghai"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
</aop:config>
</beans>
第二步:
一开始,就提示 Spring 需要扫描注解的包,所以在配置类中,进行扫描的配置:
package com.spring.config;
import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
/**
* Spring 的配置类,相当于 bean.xml
*/
@Configuration
@ComponentScan(value = "com.spring")
public class SpringConfiguration {
}
然后,删除配置文件中的:
<context:component-scan base-package="com.spring"></context:component-scan>
第三部:
接下来,在配置文件中,进行了数据源和 jdbcTemplate 的配置,所以,为了使用配置来配置,我们需要新建一个 数据库 配置类,在 config 包下创建一个新的类,名为 JdbcConfig:
package com.spring.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
/**
* 和连接数据库相关的配置类
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 创建 JdbcTemplate 对象
* @param dataSource
* @return
*/
@Bean("jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
/**
* 创建一个数据源对象
* @return
*/
@Bean(name = "dataSource")
public DataSource createDataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
由于需要对数据库连接进行配置,所以,在 resources 资源文件夹下创建一个jdbcConfig.properties 文件:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root
然后,为了引用该 properties 文件,需要在主配置类(SpringConfiguration)中使用注解,@PropertySource(“classpath:jdbcConfig.properties”)
,与此同时,为了在配置类中使用 jdbcConfig 配置类,需要 @Import
进行导入:
@Configuration
@ComponentScan(value = "com.spring")
@Import({JdbcConfig.class)
@EnableTransactionManagement
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
删去配置文件中的:
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring?serverTimezone=Asia/Shanghai"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
第四步:
使用注解来配置事务管理器。在 config 包下创建另一个配置类,名为:TransactionConfig
。
在TransactionConfig
,创建事务管理器对象:
package com.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* 和事务相关的配置类
*/
public class TransactionConfig {
/**
* 用于创建事务管理器对象
* @param dataSource
* @return
*/
@Bean("transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
为了在主配置文件中使用,需要导入到主配置文件中,同时开启事务管理器:
package com.spring.config;
import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
/**
* Spring 的配置类,相当于 bean.xml
*/
@Configuration
@ComponentScan(value = "com.spring")
@Import({JdbcConfig.class, TransactionConfig.class})
@EnableTransactionManagement
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
最后,将配置文件删去。
配置完成!
6. Spring 编程式事务控制
如果我们需要通过编程而不是在注解或者 xml 文件中进行配置来达到对事物的控制,我们就需要一个类,这个类就是 org.springframework.transaction.support.TransactionTemplate
而且,使用编程式事务控制必须借助 xml 文件来进行配置:
首先在,在 xml 文件中进行事务模板的配置:
<!-- 事务模板对象 -->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
然后我们观察这个类,其中有一个方法,这个方法是 execute 方法:
@Override
@Nullable
public <T> T execute(TransactionCallback<T> action) throws TransactionException {
Assert.state(this.transactionManager != null, "No PlatformTransactionManager set");
if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
}
else {
TransactionStatus status = this.transactionManager.getTransaction(this);
T result;
try {
result = action.doInTransaction(status);
}
catch (RuntimeException | Error ex) {
// Transactional code threw application exception -> rollback
rollbackOnException(status, ex);
throw ex;
}
catch (Throwable ex) {
// Transactional code threw unexpected exception -> rollback
rollbackOnException(status, ex);
throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
}
this.transactionManager.commit(status);
return result;
}
}
这个方法就是我们用来进行事务控制的方法。这个方法的参数是 TransactionCallback 类型的对象。在这个方法中,首先进行判断,这个判断暂且不看,主要是下面else 语句中的,如果这个执行结果抛出错误或者异常,就回滚。没有就执行通过。
所以在使用的时候,将需要进行事务控制的业务层代码放入该方法中:
@Override
public void transfer(String sourceName, String targetName, Float money) {
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targetName);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
accountDao.updateAccount(source);
accountDao.updateAccount(target);
return null;
}
});
}
但是,进行编程式事务控制,就会产生一个问题,这个问题在于每当有一个业务层方法需要进行事务控制,我们就必须将该代码重复写一遍,这就和 aop 原则相违背。所以在一般情况下,编程式事物控制,不使用。