引出事务
@Repository
public class TransferDaoImpl implements TransferDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void reduceMoney() {
String sql = "update account set money = money - ? where name = ?";
jdbcTemplate.update(sql,100,"Jack");
}
@Override
public void addMoney() {
String sql = "update account set money = money + ? where name = ?";
jdbcTemplate.update(sql,100,"Tom");
}
}
@Service
public class TransferService {
@Autowired
private TransferDao transferDao;
//转帐
public void transfer() {
// 减少钱
transferDao.reduceMoney();
//模拟异常
int i = 1/0;
//增加钱
transferDao.addMoney();
}
}
异常时,只减少了钱,没有增加钱。
事务操作过程(编程式事务管理)
//转帐
public void transfer() {
try{
//第一步 开启事务
//第二步 进行业务操作
// 减少钱
transferDao.reduceMoney();
//模拟异常
int i = 1/0;
//增加钱
transferDao.addMoney();
//第三步 没有发生异常,提交事务
}catch (Exception e){
//第四步 出现异常,事务回滚
}
}
Spring事务管理介绍
1、事务添加到JavaEE三层结构里面Service层(业务逻辑层)
2、在Spring进行事务管理操作
(1)有两种方式:编程式事务管理和声明式事务管理(使用)
编程式就是写代码,上面那种
3、声明式事务管理
(1)基于注解方式(使用)
(2)基于xml配置文件方式
4、在Spring进行声明式事务管理,底层使用AOP原理
5、Spring事务管理API
(1)提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类
事务管理器:
声明书事务-注解方式
1.在spring配置文件中配置事务管理器
当前jdbcTemplate所以使用DataSourceTransactionManager
<!--创建事务管理器-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
2.在spring配置文件,开启事务注解
(1)引入tx名称空间
<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: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">
(2)开启事务注解
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven>
3、在service类上面(或者service类里面方法上面)添加事务注解
(1)@Transactional,这个注解添加到类上面,也可以添加方法上面
(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务
(3)如果把这个注解添加方法上面,只为这个方法添加事务
@Service
@Transactional
public class TransferService {
}