SpringBoot系列:Spring Boot多数据源,Mybatis动态数据源方式
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.example.mapper.dynamic", sqlSessionTemplateRef = "dynamicSqlSessionTemplate")
public class DynamicDataSourceConfig {
@Bean(name = "dynamicDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.dynamic")
public DataSource dynamicDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dynamicSqlSessionFactory")
@Primary
public SqlSessionFactory dynamicSqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dynamicDataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/dynamic/*.xml"));
return bean.getObject();
}
@Bean(name = "dynamicTransactionManager")
@Primary
public DataSourceTransactionManager dynamicTransactionManager(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) {
return new DataSourceTransactionManager(dynamicDataSource);
}
@Bean(name = "dynamicSqlSessionTemplate")
@Primary
public SqlSessionTemplate dynamicSqlSessionTemplate(@Qualifier("dynamicSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
这个代码示例展示了如何在Spring Boot应用程序中配置和使用多个数据源。它定义了一个名为dynamicDataSource
的数据源,以及相应的SqlSessionFactory
、TransactionManager
和SqlSessionTemplate
。通过@MapperScan
注解,指定了使用这个数据源的mapper接口所在的包。这个配置适用于需要根据不同的数据源执行SQL操作的场景,如多租户系统或者按功能划分模块的数据库。
评论已关闭