Springboot配置多数据源
Springboot配置多数据源
业务中会存在同时操作多个数据库的情况,这种情况下可以创建配置类,添加数据源。大致步骤为:
- mapper分包,将操作对象为同一数据库的mapper放在同一个包内
- 修改配置文件的数据源
- 添加配置类
1.mapper分包
2.修改配置源
连接多个数据库时,url要更改为jdbc-url,否则会报错(这里改成jdbcUrl也可)
spring.datasource.datasource1.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.datasource2.type=com.alibaba.druid.pool.DruidDataSource
#datasource1
spring.datasource.datasource1.jdbcUrl=jdbc:mysql://localhost:3306/bobospace?useSSL=false&allowMultiQueries=true
spring.datasource.datasource1.username=root
spring.datasource.datasource1.password=root
# datasource2
spring.datasource.datasource2.jdbcUrl=jdbc:mysql://localhost:3306/space?useSSL=false&allowMultiQueries=true
spring.datasource.datasource2.username=root
spring.datasource.datasource2.password=root
3.添加配置类,返回构建的数据源
@Configuration
public class DataSourceConfig {
@Bean("dataSource1")
@ConfigurationProperties("spring.datasource.datasource1")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean("dataSource2")
@ConfigurationProperties("spring.datasource.datasource2")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
}
4.添加配置类,返回不同数据库对应操作对象SqlSessionFactory
- 单数据库下启动类如果有MapperScan要去掉
- 有xml配置的mapper也要重新在配置类中进行路径定位
factoryBean.setMapperLocations
@Configuration
@MapperScan(basePackages = "com.example.bobosapce.Dao.Mapper.Source1", sqlSessionFactoryRef = "sqlSessionFactory1")
public class MybatisConfig1 {
@Autowired
@Qualifier("dataSource1")
private DataSource dataSource1;
@Bean("sqlSessionFactory1")
public SqlSessionFactory sqlSessionFactory1() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource1);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/source1/*.xml"));
// 设置 MyBatis 配置
// ...
return factoryBean.getObject();
}
}
@Configuration
@MapperScan(basePackages = "com.example.bobosapce.Dao.Mapper.Source2", sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisConfig2 {
@Autowired
@Qualifier("dataSource2")
private DataSource dataSource2;
@Bean("sqlSessionFactory2")
public SqlSessionFactory sqlSessionFactory2() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource2);
// 设置 MyBatis 配置
// ...
return factoryBean.getObject();
}
}
关于SqlSessionFactory
SqlSessionFactoryBuilder 与 SqlSessionFactoryBean的区别:
mybatis中使用SqlSessionFactoryBuilder获得SqlSessionFactory 的实例,通过SqlSessionFactory 的实例可以获得操作数据的SqlSession实例,通过这个实例对数据库进行操作;
mybatis-spring整合时使用SqlSessionFactoryBean替代SqlSessionFactoryBuilder来创建session工厂.