Springboot配置多数据源

1 新建库,表

image.png

2 禁止项目读取peoperties数据库配置并自动配置数据源

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

3 配置多数据源

@Configuration
public class DataSourceConfig {
    /**
     * spring.datasource.db1
     * 数据库配置前缀
     * @return
     */
    @Bean(name = "db1")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource db1() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "db2")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource db2() {
        return DataSourceBuilder.create().build();
    }
}

4 数据库DB1配置

/**

 * 数据库1配置
 */
@Configuration
@MapperScan(basePackages = {"datasource.demo.Mapper.DB1"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class DB1Config {

    @Autowired
    @Qualifier("db1")
    private DataSource db1;

    @Bean
    public SqlSessionFactory sqlSessionFactory1() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(db1);
    // xml文件位置
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:DB1Mapper/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1());
        return template;
    }
}

5 数据库DB2配置

@Configuration

@MapperScan(basePackages = {"datasource.demo.Mapper.DB2"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class DB2Config {

    @Autowired
    @Qualifier("db2")
    private DataSource db2;

    @Bean
    public SqlSessionFactory sqlSessionFactory2() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(db2);
        // xml文件位置
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:DB2Mapper/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());
        return template;
    }
}

6 新建Mapper文件夹,路径跟数据库配置一样

image.png

7 新建xml文件夹,同上

image.png

8 测试,方便测试,直接在controller层引用dao层

@RestController

@RequestMapping("/test")
public class TestController {
    @Autowired
    DB1Mapper db1Mapper;

    @Autowired
    DB2Mapper db2Mapper;

    @GetMapping("/db1")
    public List getAll() {
        return db1Mapper.selectAll();
    }

    @GetMapping("/db2")
    public List getAll2() {
        return db2Mapper.selectAll();
    }
}

9 结果

DB2


image.png

DB1


image.png

你可能感兴趣的:(Springboot配置多数据源)