SpringBoot 多数据源 MyBatis 配置详解
在 Spring Boot 中配置多数据源 MyBatis 可以通过以下步骤实现:
- 引入依赖
 
首先需要在pom.xml文件中引入mybatis-spring-boot-starter和mysql-connector-java依赖:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>
- 配置数据源
 
在application.properties中配置数据源信息:
# 主数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/main_db?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 从数据源配置
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondary_db?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.secondary.username=root
spring.datasource.secondary.password=123456
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
这里配置了两个数据源,一个是主数据源,一个是从数据源。
- 配置 MyBatis
 
在application.properties中配置 MyBatis 信息:
# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/**/*.xml
mybatis.type-aliases-package=com.example.demo.model
mybatis.configuration.map-underscore-to-camel-case=true
这里配置了mapper文件的路径,实体类的包名和map-underscore-to-camel-case为true表示开启驼峰命名规则。
- 配置数据源和 MyBatis
 
在DataSourceConfig类中配置数据源和 MyBatis:
@Configuration
@MapperScan(basePackages = "com.example.demo.mapper")
public class DataSourceConfig {
    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/**/*.xml"));
        bean.setTypeAliasesPackage("com.example.demo.model");
        bean.setConfiguration(mybatisConfiguration());
        return bean.getObject();
    }
    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(secondaryDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/**/*.xml"));
        bean.setTypeAliasesPackage("com.example.demo.model");
        bean.setConfiguration(mybatisConfiguration());
        return bean.getObject();
    }
    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    @Bean(name = "secondarySqlSessionTemplate")
    public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory secondarySqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(secondarySqlSessionFactory);
    }
    @Bean
    public org.apache.ibatis.session.Configuration mybatisConfiguration() {
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        return configuration;
    }
}
这里配置了两个数据源和两个SqlSessionFactory,@Primary注解表示主数据源,@Qualifier注解指定注入哪个数据源,@MapperScan注解指定Mapper接口的包名。
- 使用多数据源
 
在需要使用数据源的地方注入对应的SqlSessionTemplate即可:
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    @Qualifier("sqlSessionTemplate")
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    @Qualifier("secondarySqlSessionTemplate")
    private SqlSessionTemplate secondarySqlSessionTemplate;
    @Override
    public List<User> getUsers() {
        return sqlSessionTemplate.selectList("com.example.demo.mapper.UserMapper.getUsers");
    }
    @Override
    public List<Order> getOrders() {
        return secondarySqlSessionTemplate.selectList("com.example.demo.mapper.OrderMapper.getOrders");
    }
}
这里分别注入了主数据源和从数据源的SqlSessionTemplate,使用对应的Mapper接口即可。
原文地址: https://www.cveoy.top/t/topic/ouiW 著作权归作者所有。请勿转载和采集!