目录
项目搭建参考:
从零开始搭建SpringBoot项目_从0搭建springboot项目-CSDN博客
SpringBoot学习笔记(二) 整合redis+mybatis+Dubbo-CSDN博客
添加依赖
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-lang3artifactId>
- <version>3.5version>
- dependency>
-
- <dependency>
- <groupId>org.mybatis.spring.bootgroupId>
- <artifactId>mybatis-spring-boot-starterartifactId>
- <version>2.2.2version>
- dependency>
-
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>5.1.31version>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <version>1.16.10version>
- dependency>
- dependencies>
增加数据库配置
- spring.datasource.primary.jdbc-url=jdbc:mysql://xxxx/table01?useUnicode=true&autoReconnect=true&zeroDateTimeBehavior=convertToNull
- spring.datasource.primary.username=xxxxx
- spring.datasource.primary.password=xxxxx
- spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
-
- spring.datasource.second.jdbc-url=jdbc:mysql://xxxxx/table02?useUnicode=true&autoReconnect=true&&zeroDateTimeBehavior=convertToNull
- spring.datasource.second.username=xxxxx
- spring.datasource.second.password=xxxxx
- spring.datasource.second.driver-class-name=com.mysql.jdbc.Driver
添加配置类
PrimaryDbConfig.java
- @Configuration
- @MapperScan(basePackages = {"com.ziroom.dao.primary"}, sqlSessionFactoryRef = "primarySqlSessionFactory")
- public class PrimaryDbConfig {
-
- @Primary // 这里要添加@Primary,在匹配不到数据源时,primaryData会作为默认数据源
- @Bean(name = "primaryData")
- @ConfigurationProperties(prefix = "spring.datasource.primary")
- public DataSource financeData() {
- return DataSourceBuilder.create().build();
- }
-
- @Bean(name = "primarySqlSessionFactory")
- @Primary
- public SqlSessionFactory loanSqlSessionFactory(@Qualifier("primaryData") DataSource dataSource) throws Exception {
- SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
- bean.setDataSource(dataSource);
- bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
- return bean.getObject();
- }
-
- @Bean(name = "primarySqlSessionTemplate")
- @Primary
- public SqlSessionTemplate loanSqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
- return new SqlSessionTemplate(sqlSessionFactory);
- }
- }
-
- // 事务配置
- @Bean(name = "primaryTransactionManager")
- @Primary
- public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("primaryData") DataSource dataSource)
- {
- return new DataSourceTransactionManager(dataSource);
- }
SecondDbConfig.java
- @Configuration
- @MapperScan(basePackages = {"com.ziroom.dao.second"}, sqlSessionFactoryRef = "secondSqlSessionFactory")
- public class SecondDbConfig {
-
- @Bean(name = "secondData")
- @ConfigurationProperties(prefix = "spring.datasource.second")
- public DataSource financeData() {
- return DataSourceBuilder.create().build();
- }
-
- @Bean(name = "secondSqlSessionFactory")
- public SqlSessionFactory loanSqlSessionFactory(@Qualifier("secondData") DataSource dataSource) throws Exception {
- SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
- bean.setDataSource(dataSource);
- bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
- return bean.getObject();
- }
-
- @Bean(name = "secondSqlSessionTemplate")
- public SqlSessionTemplate loanSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
- return new SqlSessionTemplate(sqlSessionFactory);
- }
- }
-
- // 事务配置
- @Bean(name = "secondTransactionManager")
- public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("secondData") DataSource dataSource) {
- return new DataSourceTransactionManager(dataSource);
- }
添加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,但是配置多数据源时手动指定了引用(见下),则上述配置依然需要排除
- @Bean(name = "dataSourcePayClearing")
- @Primary
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource dataSource(){
- return DataSourceBuilder.create().build();
- }
添加测试类
- @ResponseBody
- @RequestMapping(value = "/testPrimary")
- public String testPrimary(){
- Budget budget = new Budget();
- List
budgets = budgetMapper.queryBudgetActualList(budget); - log.info("Primary 数据源查询 size:{}", budgets.size());
- return "success";
- }
-
- -- 输出:Primary 数据源查询 size:30
-
- @ResponseBody
- @RequestMapping(value = "/testSecond")
- public String testSecond(){
- Invoice invoice = new Invoice();
- List
invoices = invoiceMapper.selectListByParams(invoice); - log.info("Second 数据源查询 size:{}", invoices.size());
- return "success";
- }
- -- 输出:Second 数据源查询 size:40
PrimaryDbConfig.java中增加
- @Bean(name = "primaryTransactionManager")
- public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("primaryData") DataSource dataSource) {
- return new DataSourceTransactionManager(dataSource);
- }
SecondDbConfig.java中增加
- @Bean(name = "secondTransactionManager")
- public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("secondData") DataSource dataSource) {
- return new DataSourceTransactionManager(dataSource);
- }
测试类 BudgetService.java
- @Service
- public class BudgetService {
-
- @Autowired
- private BudgetMapper budgetMapper;
-
- @Autowired
- private InvoiceMapper invoiceMapper;
-
-
- @Transactional(value="primaryTransactionManager",rollbackFor = RuntimeException.class)
- public void saveBudget(Budget budget) {
- budget.setBudgetYear(1);
- budget.setBudgetMonth(1);
- budget.setPartner("2");
- budgetMapper.insertSelective(budget);
- if(true){
- throw new RuntimeException("数据源1抛出异常");
- }
- }
-
- @Transactional(value="secondTransactionManager",rollbackFor = RuntimeException.class)
- public void saveInvoice(Invoice invoice) {
- invoice.setPostingDate(new Date());
- invoice.setAdvancePayment("x");
- invoice.setInvoiceDate(new Date());
- invoice.setJournalDate(new Date());
- invoice.setAllocateRowNo(1);
- invoiceMapper.insertSelective(invoice);
- if(true){
- throw new RuntimeException("数据源2抛出异常");
- }
-
- }
- }
启动类加:@EnableTransactionManagement
