事务的概念
事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败
事务的特性(不过多赘述)
(1)原子性
(2)一致性
(3)隔离性
(4)持久性
用Spring对事务进行操作,先准备好事务的操作环境:
1、创建数据库表,添加记录
2、创建 service,搭建 dao,完成对象创建和注入关系
@Service(value = "userService2")
public class userService {
@Autowired
private userdao userdao;
public void accountMoney(){
userdao.reduceMoney();
userdao.addMoney();
}
}
3、在 dao 创建两个方法:多钱和少钱的方法,在 service 创建方法(转账的方法)
@Component
public interface userdao {
public void reduceMoney();
int i = 10 / 0; //模拟异常
public void addMoney();
}
@Component
public class userdaoImpl implements userdao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void reduceMoney() {
String sql = "update t_account set money = money-? where username=?";
jdbcTemplate.update(sql,100,"Lucy");
}
@Override
public void addMoney() {
String sql = "update t_account set money = money+? where username=?";
jdbcTemplate.update(sql,100,"Mary");
}
}
由于在加钱和减钱之间出现了异常,数据库内的数据总和就会出错,接下来用事务来解决这一问题。
在 Spring 进行事务管理操作(使用注解)
1、在 spring 配置文件配置事务管理器
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
2、在 spring 配置文件,开启事务注解
(1)在 spring 配置文件引入名称空间 tx(添加下面两端代码即可)
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation中添加www.springframework.org/schema/tx www.springframework.org/schema/tx/s…
(2)开启事务注解
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
3、在 service 类上面(或者 service 类里面方法上面)添加事务注解 (上面代码已添加)
对Transactional注解的说明:
(1)@Transactional,这个注解添加到类上面,也可以添加方法上面
(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务
(3)如果把这个注解添加方法上面,为这个方法添加事务
(4)在这个注解里面可以配置事务相关参数(下面进行介绍)
@Transactional参数的说明
1.propagation:事务传播行为(多事务方法直接进行调用,这个过程中事务是如何进行管理的)
格式:propagation = Propagation.xxxxxxx
2.ioslation:事务隔离级别(与数据库隔离级别相同,再次不多赘述)
通过设置事务隔离级别,解决读问题
3、timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是 -1 ,设置时间以秒单位进行计算
4、readOnly:是否只读
5、rollbackFor:回滚
6、noRollbackFor:不回滚