Spring中的事务控制
1. Spring事务控制我们要明确的
第一:JavaEE体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计业务层的事务处理解决方案。
第二:Spring 框架为我们提供了一组事务控制的接口。在spring-tx-4.2.3.RELEASE.jar 中。
第三:Spring 的事务控制都是基于AOP的,它既可以使用编程的方式实现,也可以使用配置的方式实现。
2. Spring事务控制的API介绍
2.1 PlatformTransactionManager
此接口是Spring的事务管理器,里面提供了很多我们常用的操作事务的方法。
我们用的都是他的实现类,真正管理事务的对象:
- org.springframework.jdbc.datasource.DataSourceTransactionManager 使用 Spring
JDBC 或 Mybatis 进行持久化数据时使用 - org.springframework.orm.hibernate5.HibernateTransactionManager 使用
Hibernate 版本进行持久化数据时使用
2.2 TransactionDefinition
2.3 事务的隔离级别
2.3 事务的传播行为
- REQUIRED:如果没有当前事务,就新建一个事务,如果已经存在一个事务中,就加入到这个事务中。一般的选择(默认值)。
- SUPPORTS:支持当前事务,如果当前没有事务,就以非事务的方式执行(没有事务)。
- MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
- REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
- NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
- NEVER:以非事务方式运行,如果当前存在事务,抛出异常
- NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作
2.4 超时时间
默认值是-1,没有超时限制,如果有,以秒为单位进行设置。
2.5 是否是只读事务
建议查询时设置为只读。
3. TransactionStatus
此接口提供的是事务具体的运行状态,方法介绍如下图:
4. 基于XML的声明式事务控制(配置方式)
4.1 环境搭建
(1)导入需要的jar包。
(2)创建Spring的配置文件并导入约束
此处需要导入aop和tx两个名称空间。
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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">
</beans>
(3)准备数据库表和实体类
创建数据库:
create database mydb;
use mydb;
创建表:
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
/**
* 账户的实体类
*/
public class Account implements Serializable {
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 +
'}';
}
}
(4)编写业务层接口和实体类
/**
* 账户的业务层接口
*/
public interface IAccountService {
/**
* 根据账户名称查询账户信息
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 转账
* @param sourceName:转出账户名称
* @param targetName:张如账户名称
* @param money:转账金额
*/
public void transfer(String sourceName,String targetName,Float money);
}
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//1.根据名称查询账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targetName);
//2.转出账户减钱,转入账户加钱
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
//3.更新账户信息
accountDao.updateAccount(source);
int i = 1/0;
accountDao.updateAccount(target);
}
}
(5)编写Dao接口和实体类
/**
* 账户的接口
*/
public interface IAccountDao {
/**
* 根据id查询账户信息
*/
public Account findAccountById(Integer id);
/**
* 根据名称查询账户信息
*/
public Account findAccountByName(String name);
/**
* 更新账户信息
*/
public void updateAccount(Account account);
}
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//1.根据名称查询账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targetName);
//2.转出账户减钱,转入账户加钱
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
//3.更新账户信息
accountDao.updateAccount(source);
int i = 1/0;
accountDao.updateAccount(target);
}
}
(6)在配置文件中配置业务层和持久层
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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">
<!--配置service-->
<bean id="accountService" class="com.renjing.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置dao-->
<bean id="accountDao" class="com.renjing.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property><!--配置关联的数据源-->
</bean>
<!--配置Spring内置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
</beans>
5. 配置步骤
5.1 第一步:配置事务管理器
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
5.2 第二步:配置事务的通知引用事务管理器
<tx:advice id="txAdvice" transaction-manager="transactionManager">
</tx:advice>
5.3 第三步:配置事务的属性
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--指定方法名称:是业务核心方法
read-only:是否是只读事务。默认false,不只读。
isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。mysql为REPEATABLE-READ
propagation:指定事务的传播行为。
timeout:指定超时时间。默认值为-1.永不超时。
rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。没有默认值,任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,任何异常都会滚。-->
<tx:method name="*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
5.4 配置AOP切入点表达式
<aop:config>
<!--切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.renjing.service.impl.*.*(..))"></aop:pointcut>
</aop:config>
5.5 配置切入点表达式和事务通知的对应关系
<aop:config>
<!--切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.renjing.service.impl.*.*(..))"></aop:pointcut>
<!--建立事务的通知和切入点表达式之间的关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
5.6 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: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/cache
http://www.springframework.org/schema/cache/spring-cache.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">
<!--配置service-->
<bean id="accountService" class="com.renjing.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置dao-->
<bean id="accountDao" class="com.renjing.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property><!--配置关联的数据源-->
</bean>
<!--配置Spring内置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--Spring基于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:attributes>
<tx:method name="*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!--第三步:配置aop:切入点表达式,通知和切入点表达式的关联-->
<aop:config>
<!--切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.renjing.service.impl.*.*(..))"></aop:pointcut>
<!--建立事务的通知和切入点表达式之间的关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
6. 基于注解的配置方式
(1)使用上面的代码进行修改即可,故配置的环境相同。此处不再赘述。
(2)将业务层接口和实现类交给Spring管理。
/**
* 业务层的实现类
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)//只读型
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//1.根据名称查询账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targetName);
//2.转出账户减钱,转入账户加钱
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
//3.更新账户信息
accountDao.updateAccount(source);
int i = 1/0;
accountDao.updateAccount(target);
}
}
(3)将Dao层接口和实现类交给Spring管理。
/**
* 账户的持久层实现类
* 需要给dao注入JdbcTemplate
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Account findAccountById(Integer id) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> accounts = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
if (accounts.isEmpty()) {//此处不需要判断list是否为null,因为在封装数据的时候,肯定已经有一个list了
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一,请检查数据");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set money = ? where id = ?",account.getMoney(),account.getId());
}
}
(4)配置步骤
①开启创建Spring容器时要扫描的包。
<context:component-scan base-package="com.renjing"></context:component-scan>
②配置jdbcTemplate。
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--必须要注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
③配置Spring内置数据源。
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
④配置事务管理器并注入数据源。
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
⑤开启Spring对注解事务的支持。
<tx:annotation-driven transaction-manager="transactionManager"/>
⑥在业务层使用@Transactional注解。
(在需要事务的地方使用@Transactional注解)
/**
* 业务层的实现类
*/
@Service("accountService")
@Transactional(readOnly = false,propagation = Propagation.REQUIRED)//读写型事务
public class AccountServiceImpl implements IAccountService {
/**
* @Transactional注解:该注解的属性和xml中的属性含义一致.该注解可以出现在接口上,类上,方法上.
* 出现在接口上,表示该接口的所有方法都有事务支持.
* 出现在类上,表示类中所有方法有事务支持.
* 出现在方法上,表示方法有事务支持.
* 以上三个位置优先级:方法>类>接口
*/
@Autowired
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)//只读型
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//1.根据名称查询账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targetName);
//2.转出账户减钱,转入账户加钱
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
//3.更新账户信息
accountDao.updateAccount(source);
int i = 1/0;
accountDao.updateAccount(target);
}
}
- 纯注解配置方式
/**
* 链接数据库的配置类
*/
public class JdbcConfig {
@Bean(name = "jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "dataSource")
public DataSource createDataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/mydb");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
}
/**
* 事务控制的配置类
*/
public class TransactionManager {
@Bean(name = "transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
/**
* Spring的配置类
*/
@Configuration
@ComponentScan("com.renjing")
@Import({JdbcConfig.class, TransactionManager.class})
@EnableTransactionManagement//开启Spring对注解aop的支持
public class SpringConfiguration {
}