视频讲解:https://www.bilibili.com/video/av47952931?p=75
Spring事务控制
- JavaEE 体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方案,
- Spring 框架为我们提供了一组事务控制的接口,这组接口在spring-tx-5.0.2.RELEASE.jar中
- Spring 的事务控制都是基于AOP的,它既可以使用配置的方式实现,也可以使用编程的方式实现.推荐使用配置方式实现.
数据库事务的基础知识
使用Spring进行事务控制
Spring配置式事务控制
- 导入jar包到项目的lib目录
- 创建bean.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/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>
- 准备数据库表和实体类
创建数据库表如下
create database learnSpringTransaction; --创建数据库
use learnSpringTransaction;
-- 创建表
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)charset=utf8;
- 准备java实体类如下
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 + '}'; }
}
- 编写Service层接口和实现类
Service层接口
// 业务层接口
public interface IAccountService {
// 根据id查询账户信息
Account findAccountById(Integer accountId);
// 转账
void transfer(String sourceName,String targetName,Float money);
}
Service层实现类
// 业务层实现类,事务控制应在此层
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("start transfer");
// 1.根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
// 2.根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
// 3.转出账户减钱
source.setMoney(source.getMoney() - money);
// 4.转入账户加钱
target.setMoney(target.getMoney() + money);
// 5.更新转出账户
accountDao.updateAccount(source);
int i = 1 / 0;
// 6.更新转入账户
accountDao.updateAccount(target);
}
}
- 编写Dao层接口和实现类
Dao层接口
// 持久层接口
public interface IAccountDao {
// 根据Id查询账户
Account findAccountById(Integer accountId);
// 根据名称查询账户
Account findAccountByName(String accountName);
// 更新账户
void updateAccount(Account account);
}
Dao层实现类
//持久层实现类
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
// 根据id查询账户
@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.isEmpty()) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一");
}
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());
}
}
- 在bean.xml中配置数据源以及要扫描的包
<!--配置 创建Spring容器时要扫描的包-->
<context:component-scan base-package="com.itheima"></context:component-scan>
<!--配置 数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<!--配置 JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
- 配置事务管理器并注入数据源
<!--向Spring容器中注入一个事务管理器,这个里面包含了提交事务和回滚事务-->
<bean id="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="*" propagation="REQUIRED" read-only="false" rollback-for="" no-rollback-for=""/>
<!--匹配指定包下的所有查询方法-->
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<!--第二个<tx:method>匹配得更精确,所以对所有查询方法,匹配第二个事务管理配置;对其他查询方法,匹配第一个事务管理配置-->
</tx:attributes>
</tx:advice>
- 配置AOP并为事务管理器事务管理器指定切入点
<!--配置AOP-->
<aop:config>
<!-- 配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* cn,maoritian.service.impl.*.*(..))"></aop:pointcut>
<!--为事务通知指定切入点表达式-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
使用半注解配置事务控制
- 配置事务管理器并注入数据源
<!--向Spring容器中注入一个事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
- 在业务层使用@Transactional注解,其参数与tx:method的属性一致.
该注解可以加在接口,类或方法上
- 对接口加上@Transactional注解,表示对该接口的所有实现类进行事务控制
- 对类加上@Transactional注解,表示对类中的所有方法进行事务控制
- 对具体某一方法加以@Transactional注解,表示对具体方法进行事务控制
三个位置上的注解优先级依次升高
// 业务层实现类,事务控制应在此层
@Service("accountService")
@Transactional(propagation = Propagation.REQUIRED, readOnly = false) // 读写型事务配置
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true) // 只读型事务配置,会覆盖上面对类的读写型事务配置
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
// 转账操作的实现...
}
}