Springboot项目整合MyBatis配置多数据源
描述
在项目开发过程中,在实际的业务中总会遇到这样的问题,需要访问不同的数据源来完成数据的转移或者数据的分开处理,这个时候我们可能就需要用到在一个项目中配置多个数据源;接下来要说的是MyBatis所对应的多数据源配置的详细操作。
准备工作
项目中必须包含以下包引用(版本根据项目实际情况定):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<optional>true</optional>
</dependency>
项目过程
项目中使用的是application.yml文件来完成配置信息的,配置如下:
test:
datasource:
db1:
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://saas.database:3306/test_one
db2:
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://saas.database:3306/test_two
数据源类编写详情如下:
DB1:
@Configuration
@MapperScan(value = "tech.test.eaglehorn.mapper.db1", sqlSessionFactoryRef = "sqlSessionFactoryOne")
public class ThirdPartMybatisConfig {
@Bean
@ConfigurationProperties(prefix = "thirdpart.datasource.db1")
public DataSource dataSourceOne() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean
public SqlSessionFactory sqlSessionFactoryOne(@Qualifier("dataSourceOne") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
"classpath*:sqlmapper/db1/*.xml"
));
return sqlSessionFactoryBean.getObject();
}
}
DB2:
@Configuration
@Slf4j
@MapperScan(value = "tech.test.eaglehorn.mapper.db2", sqlSessionFactoryRef = "sqlSessionFactoryTwo")
public class GateWayMybatisConfig {
@Bean
@ConfigurationProperties(prefix = "thirdpart.datasource.db2")
public DataSource dataSourceTwo() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean
public SqlSessionFactory sqlSessionFactoryTwo(@Qualifier("dataSourceTwo") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
"classpath*:sqlmapper/db2/*.xml"
));
return sqlSessionFactoryBean.getObject();
}
}
@MapperScan注解参数中,value的值是当前数据源所对应的Mapper接口所在的包路径,sqlSessionFactoryRef的值是当前类中声明的SqlSessionFactory Bean
声明数据源bean上方上的@ConfigurationProperties(prefix = “thirdpart.datasource.db”)是项目配置中的所有信息注入;
PathMatchingResourcePatternResolver().getResources(
“classpath*:sqlmapper/db2/*.xml”
)); 这个路径是xml文件的保存路径。
总结
springboot在项目构建的过程中其实已经帮我们做了很多事情了,我们按照规定简单地做一些配置,就能满足我们基本的restful API操作数据的整个链路,完成以上的配置,将对应的mapper接口放入响应的包下,映射文件放入响应的配置目录下,然后启动项目,就可以直接写操作数据的代码逻辑了
有疑问可以评论,看到了基本上会回复