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/ghgJ 著作权归作者所有。请勿转载和采集!

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