Spring事务最顶层的接口是PlatformTransactionManager
二、传播行为
1、PROPAGATION_REQUIRED:如果当前没有事务,就创建一个新事务,如果当前存在事务,就加入该事务,该设置是最常用的设置。
2、PROPAGATION_SUPPORTS:支持当前事务,如果当前存在事务,就加入该事务,如果当前不存在事务,就以非事务执行。‘
3、PROPAGATION_MANDATORY:支持当前事务,如果当前存在事务,就加入该事务,如果当前不存在事务,就抛出异常。
4、PROPAGATION_REQUIRES_NEW:创建新事务,无论当前存不存在事务,都创建新事务。
5、PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
6、PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
7、PROPAGATION_NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作。
Spring事务
事务的四个基本特征:
① Atomic(原子性):事务中包含的操作被看做一个逻辑单元,这个逻辑单元中的操作要么全部成 功,要么全部失败。
② Consistency(一致性):事务完成时,数据必须处于一致状态,数据的完整性约束没有被破坏,事务在执行过程中发生错误,会被回滚(Rollback)到事务开始前的状态,就像这个事务从来没 有执行过一样。
③ Isolation(隔离性):事务允许多个用户对同一个数据进行并发访问,而不破坏数据的正确性 和完整性。同时,并行事务的修改必须与其他并行事务的修改相互独立。
4.Durability(持久性):事务结束后,事务处理的结果必须能够得到固化。
spring的事务分为编程式事务和声明式事务
1.spring的编程式(现在几乎是不可能用到的,以后有时间再补充例子)
通过注入TransactionTemplate,业务方法中调用TransactionTemplate的方法进行事务控制
2.spring的声明式事务
注解开启声明式事务
1.配置类加@EnableTransactionManagement,因为这里用的springJdbc,所以需要注入DataSourceTransactionManger
@Configuration
@ComponentScan("com.spring")
@EnableTransactionManagement
public class AppConfig {
@Bean
public User user(){
return new User();
}
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/xxx");
dataSource.setUsername("root");
dataSource.setPassword("tiger");
return dataSource;
}
@Bean
public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
return jdbcTemplate;
}
}
public interface UserDao {
public void update(String sql);
}
@Component
public class UserDaoImpl implements UserDao {
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
UserDao1 userDao1;
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void update(String sql) {
jdbcTemplate.update("insert into test(name,age) values('test',1)");
}
}
public interface UserDao1 {
public void update(String sql);
}
@Component
public class UserDao1Impl implements UserDao1 {
@Autowired
JdbcTemplate jdbcTemplate;
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void update(String sql) {
jdbcTemplate.update("insert into test1(name,age) values ('test1',1)");
System.out.println(1/0);
}
}
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserDao userDao = context.getBean(UserDao.class);
userDao.update("xxx");
}
}
select * from test;
+------+------+
| name | age |
+------+------+
| test | 1 |
+------+------+