- 事务机制:
- Datasource => 获取一个 connection
- connection.setAutocommit(false);
- 执行 SQL
- connection.commit();
TransactionInterceptor执行流程
传播机制:
Propagation.REQUIRED(默认机制)
@Transactional
public void test1() {
userMapper.insert1(new User("张三"));
userService.test2();
}
@Transactional
public void test2() {
userMapper.insert2(new User("李四"));
}
_
当前线程上面是不是有事务,如果有,并且是
Propagation.REQUIRED
就不会从新开启事务,而是包括在原有事务之内
- Datasource => 获取一个 connection => 保存至 ThreadLocal
- connection.setAutocommit(false);
- ThreadLocal.get() => 执行 SQL
- ThreadLocal.get() => 执行另一个包含 SQL 的业务逻辑
- connection.commit();
Propagation.REQUIRES_NEW
@Transactional
public void test1() {
userMapper.insert1(new User("张三"));
userService.test2();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void test2() {
userMapper.insert2(new User("李四"));
}
_
当前线程上面是不是有事务,如果有,并且是
Propagation.REQUIRES_NEW
就会将原来的事务挂起,并开启新的事务去执行新的逻辑,然后恢复原来的事务,提交原来的事务
- Datasource => 获取一个 connection1 => 保存至 ThreadLocal
- connection1.setAutocommit(false);
- ThreadLocal.get() => connection1 => 执行 SQL
- 继续向下执行
- 发现
Propagation.REQUIRES_NEW
- 将 connection1 挂机(从 ThreadLocal 中移除,并保存到其他地方)
- Datasource => 获取一个 connection2 => 保存至 ThreadLocal
- connection2.setAutocommit(false);
- ThreadLocal.get() => connection2 => 执行另一个包含 SQL 的业务逻辑
- connection2.commit()
- 将 connection1 恢复(从新保存到 ThreadLocal
中) - connection1.commit();
Propagation.NESTED
@Transactional
public void test1() {
userMapper.insert1(new User("张三"));
userService.test2();
}
@Transactional(propagation = Propagation.NESTED)
public void test2() {
userMapper.insert2(new User("李四"));
}
当前线程上面是不是有事务,如果有,并且是
Propagation.NESTED
就会在当前位置设置一个 savepoint,然后继续执行,如果出现了异常,只会回滚到 savepoint 这里,然后继续执行,直到提交
- Datasource => 获取一个 connection => 保存至 ThreadLocal
- connection.setAutocommit(false);
- ThreadLocal.get() => 执行 SQL
- ThreadLocal.get() => 执行另一个包含 SQL 的业务逻辑
- 继续向下执行
- 发现
Propagation.NESTED
- 设置一个 savepoint
- ThreadLocal.get() => 执行 SQL
- 如果发现异常,则回滚到 savepoint
- 继续向下执行
- connection.commit();
Propagation.NEVER
@Transactional
public void test1() {
userMapper.insert1(new User("张三"));
userService.test2();
}
@Transactional(propagation = Propagation.NEVER)
public void test2() {
userMapper.insert2(new User("李四"));
}
当前线程上面是不是有事务,如果有,并且是
Propagation.NEVER
就会直接抛异常