SpringBoot整合Mybatis-Plus、Druid配置多数据源
在Spring Boot整合MyBatis-Plus和Druid配置多数据源的过程中,你需要定义多个数据源的配置,并且为每个数据源创建一个DataSource
、SqlSessionFactory
和MybatisPlusInterceptor
实例。以下是一个简化的示例:
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.first")
public DataSource firstDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.second")
public DataSource secondDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 配置分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
@Bean
public SqlSessionFactory firstSqlSessionFactory(DataSource firstDataSource, MybatisPlusInterceptor mybatisPlusInterceptor) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(firstDataSource);
sqlSessionFactoryBean.setPlugins(mybatisPlusInterceptor);
return sqlSessionFactoryBean.getObject();
}
@Bean
public SqlSessionFactory secondSqlSessionFactory(DataSource secondDataSource, MybatisPlusInterceptor mybatisPlusInterceptor) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(secondDataSource);
sqlSessionFactoryBean.setPlugins(mybatisPlusInterceptor);
return sqlSessionFactoryBean.getObject();
}
}
在上述代码中,我们定义了两个数据源firstDataSource
和secondDataSource
,并为每个数据源创建了一个SqlSessionFactory
实例。同时,我们创建了一个MybatisPlusInterceptor
实例,并将其应用到所有的SqlSessionFactory
实例中。
确保在application.properties
或application.yml
中配置了正确的数据源属性,例如:
spring:
datasource:
druid:
first:
url: jdbc:mysql://localhost:3306/first_db
username: first_user
password: first_password
second:
url: jdbc:mysql://localhost:3306/second_db
username: second_user
pa
评论已关闭