• SpringBoot+Mybatis 配置多数据源及事务管理


    目录

    1.多数据源

    2.事务配置


    项目搭建参考:

    从零开始搭建SpringBoot项目_从0搭建springboot项目-CSDN博客

    SpringBoot学习笔记(二) 整合redis+mybatis+Dubbo-CSDN博客

    1.多数据源

    添加依赖

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework.bootgroupId>
    4. <artifactId>spring-boot-starter-webartifactId>
    5. dependency>
    6. <dependency>
    7. <groupId>org.springframework.bootgroupId>
    8. <artifactId>spring-boot-starter-testartifactId>
    9. <scope>testscope>
    10. dependency>
    11. <dependency>
    12. <groupId>org.apache.commonsgroupId>
    13. <artifactId>commons-lang3artifactId>
    14. <version>3.5version>
    15. dependency>
    16. <dependency>
    17. <groupId>org.mybatis.spring.bootgroupId>
    18. <artifactId>mybatis-spring-boot-starterartifactId>
    19. <version>2.2.2version>
    20. dependency>
    21. <dependency>
    22. <groupId>mysqlgroupId>
    23. <artifactId>mysql-connector-javaartifactId>
    24. <version>5.1.31version>
    25. dependency>
    26. <dependency>
    27. <groupId>org.projectlombokgroupId>
    28. <artifactId>lombokartifactId>
    29. <version>1.16.10version>
    30. dependency>
    31. dependencies>

    增加数据库配置

    1. spring.datasource.primary.jdbc-url=jdbc:mysql://xxxx/table01?useUnicode=true&autoReconnect=true&zeroDateTimeBehavior=convertToNull
    2. spring.datasource.primary.username=xxxxx
    3. spring.datasource.primary.password=xxxxx
    4. spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
    5. spring.datasource.second.jdbc-url=jdbc:mysql://xxxxx/table02?useUnicode=true&autoReconnect=true&&zeroDateTimeBehavior=convertToNull
    6. spring.datasource.second.username=xxxxx
    7. spring.datasource.second.password=xxxxx
    8. spring.datasource.second.driver-class-name=com.mysql.jdbc.Driver

    添加配置类

    PrimaryDbConfig.java

    1. @Configuration
    2. @MapperScan(basePackages = {"com.ziroom.dao.primary"}, sqlSessionFactoryRef = "primarySqlSessionFactory")
    3. public class PrimaryDbConfig {
    4. @Primary // 这里要添加@Primary,在匹配不到数据源时,primaryData会作为默认数据源
    5. @Bean(name = "primaryData")
    6. @ConfigurationProperties(prefix = "spring.datasource.primary")
    7. public DataSource financeData() {
    8. return DataSourceBuilder.create().build();
    9. }
    10. @Bean(name = "primarySqlSessionFactory")
    11. @Primary
    12. public SqlSessionFactory loanSqlSessionFactory(@Qualifier("primaryData") DataSource dataSource) throws Exception {
    13. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    14. bean.setDataSource(dataSource);
    15. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
    16. return bean.getObject();
    17. }
    18. @Bean(name = "primarySqlSessionTemplate")
    19. @Primary
    20. public SqlSessionTemplate loanSqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    21. return new SqlSessionTemplate(sqlSessionFactory);
    22. }
    23. }
    24. // 事务配置
    25. @Bean(name = "primaryTransactionManager")
    26. @Primary
    27. public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("primaryData") DataSource dataSource)
    28. {
    29. return new DataSourceTransactionManager(dataSource);
    30. }

    SecondDbConfig.java

    1. @Configuration
    2. @MapperScan(basePackages = {"com.ziroom.dao.second"}, sqlSessionFactoryRef = "secondSqlSessionFactory")
    3. public class SecondDbConfig {
    4. @Bean(name = "secondData")
    5. @ConfigurationProperties(prefix = "spring.datasource.second")
    6. public DataSource financeData() {
    7. return DataSourceBuilder.create().build();
    8. }
    9. @Bean(name = "secondSqlSessionFactory")
    10. public SqlSessionFactory loanSqlSessionFactory(@Qualifier("secondData") DataSource dataSource) throws Exception {
    11. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    12. bean.setDataSource(dataSource);
    13. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
    14. return bean.getObject();
    15. }
    16. @Bean(name = "secondSqlSessionTemplate")
    17. public SqlSessionTemplate loanSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    18. return new SqlSessionTemplate(sqlSessionFactory);
    19. }
    20. }
    21. // 事务配置
    22. @Bean(name = "secondTransactionManager")
    23. public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("secondData") DataSource dataSource) {
    24. return new DataSourceTransactionManager(dataSource);
    25. }

    添加mapper相关

    启动类屏蔽DataSourceAutoConfiguration.java

    注意:类似于SpringBoot学习笔记(二) 整合redis+mybatis+Dubbo-CSDN博客 中单数据源的情况,配置文件中配置了spring.datasource.* ,且@MapperScan(value = "com.xxxx.crm.demo.mapper")加到主类上,说明指定的dao关联了默认的spring.datasource.*, 这种情况则不能排除DataSourceAutoConfiguration.class

    如果配置文件中存在默认的spring.datasource.url,但是配置多数据源时手动指定了引用(见下),则上述配置依然需要排除

    1. @Bean(name = "dataSourcePayClearing")
    2. @Primary
    3. @ConfigurationProperties(prefix = "spring.datasource")
    4. public DataSource dataSource(){
    5. return DataSourceBuilder.create().build();
    6. }

    添加测试类

    1. @ResponseBody
    2. @RequestMapping(value = "/testPrimary")
    3. public String testPrimary(){
    4. Budget budget = new Budget();
    5. List budgets = budgetMapper.queryBudgetActualList(budget);
    6. log.info("Primary 数据源查询 size:{}", budgets.size());
    7. return "success";
    8. }
    9. -- 输出:Primary 数据源查询 size:30
    10. @ResponseBody
    11. @RequestMapping(value = "/testSecond")
    12. public String testSecond(){
    13. Invoice invoice = new Invoice();
    14. List invoices = invoiceMapper.selectListByParams(invoice);
    15. log.info("Second 数据源查询 size:{}", invoices.size());
    16. return "success";
    17. }
    18. -- 输出:Second 数据源查询 size:40

    2.事务配置

    PrimaryDbConfig.java中增加

    1. @Bean(name = "primaryTransactionManager")
    2. public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("primaryData") DataSource dataSource) {
    3. return new DataSourceTransactionManager(dataSource);
    4. }

    SecondDbConfig.java中增加

    1. @Bean(name = "secondTransactionManager")
    2. public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("secondData") DataSource dataSource) {
    3. return new DataSourceTransactionManager(dataSource);
    4. }

    测试类 BudgetService.java

    1. @Service
    2. public class BudgetService {
    3. @Autowired
    4. private BudgetMapper budgetMapper;
    5. @Autowired
    6. private InvoiceMapper invoiceMapper;
    7. @Transactional(value="primaryTransactionManager",rollbackFor = RuntimeException.class)
    8. public void saveBudget(Budget budget) {
    9. budget.setBudgetYear(1);
    10. budget.setBudgetMonth(1);
    11. budget.setPartner("2");
    12. budgetMapper.insertSelective(budget);
    13. if(true){
    14. throw new RuntimeException("数据源1抛出异常");
    15. }
    16. }
    17. @Transactional(value="secondTransactionManager",rollbackFor = RuntimeException.class)
    18. public void saveInvoice(Invoice invoice) {
    19. invoice.setPostingDate(new Date());
    20. invoice.setAdvancePayment("x");
    21. invoice.setInvoiceDate(new Date());
    22. invoice.setJournalDate(new Date());
    23. invoice.setAllocateRowNo(1);
    24. invoiceMapper.insertSelective(invoice);
    25. if(true){
    26. throw new RuntimeException("数据源2抛出异常");
    27. }
    28. }
    29. }

    启动类加:@EnableTransactionManagement

    代码详见https://github.com/lizhjian/SpringBootTest

  • 相关阅读:
    你的Web3域名 价值究竟何在?
    mybatis与spring集成和分页插件应用
    JS中的箭头函数
    java计算机毕业设计健身俱乐部管理系统源码+mysql数据库+系统+lw文档+部署
    【SimpleFunction系列二.3】Redisson分布式锁8种锁模式剖析
    0021Java程序设计-SSM框架图书管理系统
    普通人还有必要学习 Python 之类的编程语言吗?
    免费api接口:物流api,企业工商查询api,游戏api。。。
    SQL学习路径
    【MySQL进阶】表的增删改查操作(CRUD)+(SQL执行顺序)
  • 原文地址:https://blog.csdn.net/danxiaodeshitou/article/details/134000083