springboot+mybatis实现多数据源配置

本文介绍了如何在SpringBoot项目中集成MyBatis以实现多数据源配置。通过配置文件设置两个数据源,并创建对应的配置类进行数据源初始化。同时,为每个数据源配置了MyBatis的SqlSessionFactory和SqlSessionTemplate,以及对应的Mapper接口。在测试中展示了如何在不同数据源间切换进行数据操作。
摘要由CSDN通过智能技术生成

在日常开发中,若遇到多个数据源的需求,怎么办呢?
通过springboot集成mybatis实现多数据源配置,简单尝试一下。

  1. 新建springboot工程,引入web、mysql、mybatis依赖
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
  1. 在application.properties中配置多数据源

spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/ds0
spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/ds1
spring.datasource.secondary.username=root
spring.datasource.secondary.password=root
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver

多数据源配置与单个数据源配置不同点在于,spring.datasource之后多了一个数据源名称primary/secondary用来区分不同的数据源;

  1. 初始化数据源
    新建一个配置类,用来加载多个数据源完成初始化。
@Configuration
public class DataSourceConfiguration {

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

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

}

通过@ConfigurationProperties就可以知道这两个数据源分别加载了spring.datasource.primary.*和spring.datasource.secondary.*的配置。@Primary注解指定了主数据源,当不指定数据源时,就会使用该主数据源。

  1. mybatis配置
@Configuration
@MapperScan(
        basePackages = "com*.primary",
        sqlSessionFactoryRef = "sqlSessionFactoryPrimary",
        sqlSessionTemplateRef = "sqlSessionTemplatePrimary")
public class PrimaryConfig {

    private DataSource primaryDataSource;

    public PrimaryConfig(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
        this.primaryDataSource = primaryDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryPrimary() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(primaryDataSource);
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplatePrimary() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryPrimary());
    }

}
@Configuration
@MapperScan(
        basePackages = "com.*.secondary",
        sqlSessionFactoryRef = "sqlSessionFactorySecondary",
        sqlSessionTemplateRef = "sqlSessionTemplateSecondary")
public class SecondaryConfig {

    private DataSource secondaryDataSource;

    public SecondaryConfig(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
        this.secondaryDataSource = secondaryDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactorySecondary() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(secondaryDataSource);
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateSecondary() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactorySecondary());
    }

}

配置类上使用@MapperScan注解来指定当前数据源下定义的实体和mapper的包路径,还注入了sqlSessionFactory和sqlSessionTemplate,通过@Qualifier注解指定了对应的数据源,其名字对应在DataSourceConfiguration配置类中的数据源定义的函数名。

  1. 各个对数据源对应路径下的实体和mapper
@Data
@NoArgsConstructor
public class UserPrimary {

    private Long id;

    private String user_name;
    private Integer age;

    public UserPrimary(String name, Integer age) {
        this.user_name = name;
        this.age = age;
    }
}

public interface UserMapperPrimary {

    @Select("SELECT * FROM USER_0 WHERE USER_NAME = #{name}")
    UserPrimary findByName(@Param("name") String name);

    @Insert("INSERT INTO USER_0 (USER_NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Delete("DELETE FROM USER_0")
    int deleteAll();

}
@Data
@NoArgsConstructor
public class UserSecondary {

    private Long id;

    private String user_name;
    private Integer age;

    public UserSecondary(String name, Integer age) {
        this.user_name = name;
        this.age = age;
    }
}

public interface UserMapperSecondary {

    @Select("SELECT * FROM USER_1 WHERE USER_NAME = #{name}")
    UserSecondary findByName(@Param("name") String name);

    @Insert("INSERT INTO USER_1 (USER_NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Delete("DELETE FROM USER_1")
    int deleteAll();
}
  1. 测试
	@Test
    public void test() {
        // 往Primary数据源插入一条数据
        userMapperPrimary.insert("caocao", 20);

        // 从Primary数据源查询刚才插入的数据,配置正确就可以查询到
        UserPrimary userPrimary = userMapperPrimary.findByName("caocao");
        Assert.assertEquals(20, userPrimary.getAge().intValue());

        // 从Secondary数据源查询刚才插入的数据,配置正确应该是查询不到的
        UserSecondary userSecondary = userMapperSecondary.findByName("caocao");
        Assert.assertNull(userSecondary);

        // 往Secondary数据源插入一条数据
        userMapperSecondary.insert("sunquan", 21);

        // 从Primary数据源查询刚才插入的数据,配置正确应该是查询不到的
        userPrimary = userMapperPrimary.findByName("sunquan");
        Assert.assertNull(userPrimary);

        // 从Secondary数据源查询刚才插入的数据,配置正确就可以查询到
        userSecondary = userMapperSecondary.findByName("sunquan");
        Assert.assertEquals(21, userSecondary.getAge().intValue());
    }
  • 9
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值