1. 添加依赖

在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.21</version>
</dependency>

其中,mybatis-spring-boot-starter 是 MyBatis 的 Spring Boot starter,druid-spring-boot-starter 是阿里巴巴的 Druid 连接池的 Spring Boot starter。

  1. 配置数据源

在 application.properties/application.yml 文件中配置数据源信息,例如:

spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false
spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false
spring.datasource.secondary.username=root
spring.datasource.secondary.password=root
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver

其中,primary 和 secondary 为数据源的名称,可以自定义。

  1. 配置 MyBatis

在 MyBatis 的配置文件中,需要指定使用哪个数据源,例如:

@Configuration
@MapperScan(basePackages = {"com.example.mapper.primary"}, sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDataSourceConfig {

    @Primary
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "primarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/primary/*.xml"));
        return bean.getObject();
    }

    @Primary
    @Bean(name = "primaryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "primarySqlSessionTemplate")
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

上述代码中,我们定义了一个名为 PrimaryDataSourceConfig 的 Java 配置类,其中使用了 @MapperScan 注解来扫描 mapper 接口所在的包,并指定使用 primary 数据源。同时,我们定义了 4 个 Bean,分别是:

  • primaryDataSource:primary 数据源
  • primarySqlSessionFactory:primary SqlSessionFactory
  • primaryTransactionManager:primary 事务管理器
  • primarySqlSessionTemplate:primary SqlSessionTemplate

类似的,我们还需要为 secondary 数据源配置一个类:

@Configuration
@MapperScan(basePackages = {"com.example.mapper.secondary"}, sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class SecondaryDataSourceConfig {

    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/secondary/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "secondaryTransactionManager")
    public DataSourceTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "secondarySqlSessionTemplate")
    public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
  1. 编写 Mapper 接口

在 mapper 接口中,我们需要使用 @Mapper 注解来标识该接口为 Mapper 接口,同时需要指定使用哪个数据源。例如:

@Mapper
public interface PrimaryMapper {

    @Select("SELECT * FROM user")
    @Results(id = "userMap", value = {
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "age", column = "age")
    })
    List<User> getUsers();
}
  1. 使用 Mapper 接口访问数据库

最后,在需要访问数据库的地方,我们可以通过 @Autowired 注解来注入 Mapper 接口,然后直接调用其方法即可,例如:

@RestController
public class UserController {

    @Autowired
    private PrimaryMapper primaryMapper;

    @Autowired
    private SecondaryMapper secondaryMapper;

    @GetMapping("/users")
    public List<User> getUsers() {
        return primaryMapper.getUsers();
    }

    @GetMapping("/books")
    public List<Book> getBooks() {
        return secondaryMapper.getBooks();
    }
}

上述代码中,我们注入了 PrimaryMapper 和 SecondaryMapper,并在相应的方法中调用了它们的方法来访问数据库。

SpringBoot 多数据源 MyBatis 配置及 Mapper 接口使用教程

原文地址: https://www.cveoy.top/t/topic/ouFq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录