Spring Boot 2.x basic tutorial: MyBatis multiple data source configuration

Two days ago, we have introduced the multi-data source configuration of JdbcTemplate and the multi-data source configuration of Spring Data JPA . Next , let 's talk about how to configure the multi-data source scenario when using MyBatis.

Add the configuration of multiple data sources

First set up two database configurations that you want to link in the Spring Boot configuration file application.properties, such as this:

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

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

Description and note :

  1. When configuring multiple data sources, the difference from single data source is that after spring.datasource, one more data source name primary and secondary are set to distinguish different data source configurations. This prefix will be used in subsequent initialization of data sources.
  2. Data source connection configuration 2.x and 1.x configuration items are different: 2.x uses spring.datasource.secondary.jdbc-url, while 1.x version uses spring.datasource.secondary.url. If you get this error java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName. during configuration, then it is the problem of this configuration item.
  3. It can be seen that no matter which data access framework is used, the configuration of the data source is the same.

Initialize the data source and MyBatis configuration

After completing the configuration information of multiple data sources, create a configuration class to load the configuration information, initialize the data source, and initialize the MyBatis configuration for each data source.

Here we continue to split the data source and framework configuration:

  1. Create a separate configuration class for multiple data sources, such as the following:
@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();
    }

}

You can see that the content is exactly the same as JdbcTemplate and Spring Data JPA. It @ConfigurationPropertiescan be known that these two data sources have loaded the configuration of spring.datasource.primary.*and respectively spring.datasource.secondary.*. @PrimaryThe annotation specifies the main data source, that is, when we do not specify which data source, the real difference of this Bean will be used in the following JPA configuration.

  1. Create MyBatis configurations for the two data sources respectively.

JPA configuration of Primary data source:

@Configuration
@MapperScan(
        basePackages = "com.didispace.chapter39.p",
        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());
    }

}

JPA configuration of Secondary data source:

@Configuration
@MapperScan(
        basePackages = "com.didispace.chapter39.s",
        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());
    }

}

Description and note :

  1. @MapperScanAnnotations are used on the configuration class to specify the package path of Entity and Mapper defined under the current data source; in addition, sqlSessionFactory and sqlSessionTemplate need to be specified. These two specific implementations are initialized in the configuration class.
  2. In the constructor of the configuration class, an @Qualifierannotation is used to specify which data source to use, and its name corresponds to DataSourceConfigurationthe function name defined by the data source in the configuration class.
  3. Define the implementation of SqlSessionFactory and SqlSessionTemplate in the configuration class, pay attention to the correct data source used (if you use the demo code here, as long as the second step is ok, you don't need to modify it).

When I introduced JPA in the previous article, because when I introduced the use of JPA, I mentioned the method of entity and Repository definition, so the definition code of User and Repository was omitted, but some readers still asked why there is no such thing. In fact, there are instructions. Warehouse There is also in the code. I'm not avoiding asking such questions again, so just post it here.

According to the definition of the primary data source above, under the com.didispace.chapter39.ppackage, define the entities and data access objects to be used by the primary data source, such as the following:

@Data
@NoArgsConstructor
public class UserPrimary {

    private Long id;

    private String name;
    private Integer age;

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

public interface UserMapperPrimary {

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

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

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

}

According to the definition of the Secondary data source above, under the com.didispace.chapter39.spackage, define the entities and data access objects to be used by the Secondary data source, such as the following:

@Data
@NoArgsConstructor
public class UserSecondary {
    
    

    private Long id;

    private String name;
    private Integer age;

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

public interface UserMapperSecondary {
    
    

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

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

    @Delete("DELETE FROM USER")
    int deleteAll();
}

Test verification

After completing the above, we can write a test class to try whether the above multiple data source configuration is correct, first design a verification idea:

  1. Insert a piece of data into the Primary data source
  2. Query the data just inserted from the Primary data source, and you can query it if the configuration is correct
  3. Query the data just inserted from the Secondary data source. If the configuration is correct, it should not be queried.
  4. Insert a piece of data into the Secondary data source
  5. Query the data just inserted from the Primary data source. If the configuration is correct, it should not be queried.
  6. Query the data just inserted from the Secondary data source, and you can query it if the configuration is correct

The specific implementation is as follows:

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class Chapter39ApplicationTests {
    
    

    @Autowired
    private UserMapperPrimary userMapperPrimary;
    @Autowired
    private UserMapperSecondary userMapperSecondary;

    @Before
    public void setUp() {
    
    
        // 清空测试表,保证每次结果一样
        userMapperPrimary.deleteAll();
        userMapperSecondary.deleteAll();
    }

    @Test
    public void test() throws Exception {
    
    
        // 往Primary数据源插入一条数据
        userMapperPrimary.insert("AAA", 20);

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

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

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

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

        // 从Secondary数据源查询刚才插入的数据,配置正确就可以查询到
        userSecondary = userMapperSecondary.findByName("BBB");
        Assert.assertEquals(20, userSecondary.getAge().intValue());
    }

}

Code example

For related examples in this article, you can view the chapter3-9directories in the following warehouse :

If you think this article is good, welcome Star support, your attention is my motivation for persistence!

This article first published : Spring Boot 2.x basic tutorial: MyBatis multiple data source configuration
, please indicate the source for reprinting.
Welcome to pay attention to my official account: Program Ape DD, to get exclusive learning resources and daily dry goods push.
If you are interested in my other topics, please go directly to my personal blog: didispace.com .

Guess you like

Origin blog.csdn.net/dyc87112/article/details/106966355