SpringBoot多数据源配置之事务管理
- 1.Spring编程式事务
- 1.1 简单案例
- 2.mybatis多数据源事务
- 2.1 简单mybatis项目结构
- 2.2 application.yml配置
- 2.3 读写数据源配置
- 3.测试
1.Spring编程式事务
Spring
编程式事务是一种通过编写具体代码来实现事务管理的方式。 在编程式事务中, 开发人员需要手动编写代码来控制事务的开始、提交和回滚等操作。
1.1 简单案例
@RestController
@RequestMapping("/user")
public class UserController {@AutowiredTransactionTemplate transactionTemplate;@AutowiredUserDao userDao;@PostMapping("/a")public void insertUser1(@RequestBody User user){transactionTemplate.execute(new TransactionCallback<Object>(){@Overridepublic Object doInTransaction(TransactionStatus status) {try {userDao.inserUser(user);
// int a=1/0;return "ok";}catch (Exception e){e.printStackTrace();status.setRollbackOnly();return null;}}});}
}
直接注入TransactionTemplate
即可
2.mybatis多数据源事务
2.1 简单mybatis项目结构
2.2 application.yml配置
spring:datasource:datasource1:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3306/test_masterusername: rootpassword: rootdruid:initial-size: 1min-idle: 1max-active: 20test-on-borrow: truedatasource2:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3306/test_slaveusername: rootpassword: rootdruid:initial-size: 1min-idle: 1max-active: 20test-on-borrow: truemain:allow-bean-definition-overriding: truemybatis:type-aliases-package: com.rql.entity
# mapper-locations: classpath:mybatis/*/*.xml
2.3 读写数据源配置
RMybatisConfig.java
@Configuration
@MapperScan(basePackages = "com.rql.mapper.r",sqlSessionFactoryRef = "rsqlSessionFactory")
public class RMybatisConfig {@Bean@ConfigurationProperties(prefix = "spring.datasource.datasource2")public DataSource dataSource2(){return DataSourceBuilder.create().build();}@Beanpublic SqlSessionFactory rsqlSessionFactory() throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource2());sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/r/*.xml"));return sqlSessionFactoryBean.getObject();}@Beanpublic DataSourceTransactionManager rTransactionManager() {DataSourceTransactionManager datasource2TransactionManager =new DataSourceTransactionManager();datasource2TransactionManager.setDataSource(dataSource2());return datasource2TransactionManager;}@Beanpublic TransactionTemplate rtransactionTemplate() {return new TransactionTemplate(rTransactionManager());}
}
这里面配置了当前数据源的事务:
@Beanpublic DataSourceTransactionManager rTransactionManager() {DataSourceTransactionManager datasource2TransactionManager =new DataSourceTransactionManager();//指定事务对应的数据源 datasource2TransactionManager.setDataSource(dataSource2());return datasource2TransactionManager;}//将该数据源事务Bean注入Spring容器@Beanpublic TransactionTemplate rtransactionTemplate() {return new TransactionTemplate(rTransactionManager());}
WMybatisConfig.java
@Configuration
//继承mybatis
//1.basePackages:指定扫描的mapper接口包(主库)
//2.sqlSessionFactoryRef:指定使用sqlSessionFactory是哪个
@MapperScan(basePackages = "com.rql.mapper.w",sqlSessionFactoryRef = "wsqlSessionFactory")
public class WMybatisConfig {@Bean@ConfigurationProperties(prefix = "spring.datasource.datasource1")public DataSource dataSource1(){return DataSourceBuilder.create().build();}@Bean@Primarypublic SqlSessionFactory wsqlSessionFactory() throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource1());sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/w/*.xml"));return sqlSessionFactoryBean.getObject();}@Bean@Primarypublic DataSourceTransactionManager wTransactionManager() {DataSourceTransactionManager datasource1TransactionManager =new DataSourceTransactionManager();datasource1TransactionManager.setDataSource(dataSource1());return datasource1TransactionManager;}@Beanpublic TransactionTemplate wtransactionTemplate() {return new TransactionTemplate(wTransactionManager());}
}
3.测试
@RestController
@RequestMapping("user")
public class UserController {@Autowiredprivate RUserMapper rUserMapper;@Autowiredprivate WUserMapper wUserMapper;@AutowiredTransactionTemplate rtransactionTemplate;@AutowiredTransactionTemplate wtransactionTemplate;/** 当指定某一个数据源事务Bean为primary时,当出现异常时,事务回滚* 如果所有的数据库操作是在异常之前完成的,那么就无法做到* 所有的数据源回滚。异常之后的语句是不会执行的。* */@PostMapping("/ab")@Transactionalpublic void saveAll(){wUserMapper.inserUser(new User(10,"lili"));int a=1/0;rUserMapper.inserUser(new User(12,"long"));}@PostMapping("/abc")public void saveAll1(){wtransactionTemplate.execute((wstatus)->{rtransactionTemplate.execute((rstatus)->{try {wUserMapper.inserUser(new User(10,"lili"));rUserMapper.inserUser(new User(10,"lili"));
// int a=1/0;}catch (Exception e){e.printStackTrace();wstatus.setRollbackOnly();rstatus.setRollbackOnly();return false;}return true;});return true;});}}