spring boot mybatis multi data source solution

  Will inevitably encounter problems require the use of multiple data sources in a project in our project, I like to get a job in the user's chat migration when the time is uses three data sources, AOP was used programmatically dynamically switch data sources according to different methods of access, that is not a good performance, but also the first in a new use use, feel good, recorded.

  Introduce DEMO project, spring boot integrated mybatis use, mybatis query the database is based on the notes in the form of a query, the query purpose of user information the two databases test1 and test2 and prints in the console.

  1.pom file

 1 <dependencies>
 2         <dependency>
 3             <groupId>org.springframework.boot</groupId>
 4             <artifactId>spring-boot-starter-web</artifactId>
 5         </dependency>
 6         <dependency>
 7             <groupId>org.mybatis.spring.boot</groupId>
 8             <artifactId>mybatis-spring-boot-starter</artifactId>
 9             <version>2.1.1</version>
10         </dependency>
11         <dependency>
12             <groupId>com.alibaba</groupId>
13             <artifactId>druid-spring-boot-starter</artifactId>
14             <version>1.1.10</version>
15         </dependency>
16         <dependency>
17             <groupId>mysql</groupId>
18             <artifactId>mysql-connector-java</artifactId>
19             <scope>runtime</scope>
20             <version>5.1.27</version>
21         </dependency>
22         <dependency>
23             <groupId>org.springframework.boot</groupId>
<24             artifactId>spring-boot-starter-test</artifactId>
25             <scope>test</scope>
26             <exclusions>
27                 <exclusion>
28                     <groupId>org.junit.vintage</groupId>
29                     <artifactId>junit-vintage-engine</artifactId>
30                 </exclusion>
31             </exclusions>
32         </dependency>
33     </dependencies>
34 
35     <build>
36         <resources>
37             <resource>
38                 <directory>src/main/java</directory>
39                 <includes>
40                     <include>
41                         **/*.xml
42                     </include>
43                 </includes>
44             </resource>
45             <resource>
46                 <directory>src/resources</directory>
47             </resource>
48         </resources>
49         <plugins>
50             <plugin>
51                 <groupId>org.springframework.boot</groupId>
52                 <artifactId>spring-boot-maven-plugin</artifactId>
53             </plugin>
54         </plugins>
55     </build>
View Code

  Added a druid of alibaba data source instead of spring boot default hikacp, attention mysql drive the version number to be consistent with the version number being used by myself mysql, wherein the build inside the module resources which is to prevent the spring boot filter off src / main / java XML files, after all, some people like mybatsi query the database when using the XML mapping file, but we are using this form of comment, so <resources> content inside is not used in the project to. If the direct use annotations, you can ignore the content.

  2. User class

public class User {
    public Integer id;
    public String name;
    public String address;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
        //get set方法省略...........
}

  User class does not have much to say, it is the basic of several properties.

  3.application.properties file configuration

spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.one.username=root
spring.datasource.one.password=123456
spring.datasource.one.url=jdbc:mysql://localhost:3306/test1

spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.two.username=root
spring.datasource.two.password=123456
spring.datasource.two.url=jdbc:mysql://localhost:3306/test2

  Create a different data sources here mainly configured to access the properties of the two databases, note the difference between the two is prefixed one where two different, easy to use security class attribute spring boot in the following way.

  4. Create different data sources according to different prefixes

@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    public DataSource dsOne(){
        return DruidDataSourceBuilder.create().build();
    }
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    public DataSource dsTwo(){
        return DruidDataSourceBuilder.create().build();
    }
}

  This class is located in the main directory of the config directory, use @ConfigurationProperties annotations indicate the contents of the configuration file is created when the corresponding DataSource used.

  5. created under the main directory and are mapper1 mapper2 package to create the corresponding data access interface layer UserMapper1 UserMapper2 in the corresponding packet and the following contents are as follows

@Mapper
public interface UserMapper1 {
    @Select("select * from users")
    List<User> getAllUser();
}

  This is not much to say inside the interface is a simple mytatis annotation-based query interface to all users.

  6. Create different configurations and two classes MybatisConfigOne MybatisConfigTwo dao classes respectively correspond to scan layer interface and mapper2 mapper1 following two paths in the package below config.

@Configuration
@MapperScan(basePackages = "com.hopec.mybatis.mapper1",sqlSessionFactoryRef = "sqlSessionFactory1",
        sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MybatisConfigOne {
    @Autowired
    @Qualifier("dsOne")
    DataSource ds1;
@Bean
    SqlSessionFactory sqlSessionFactory1(){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds1);
        try {
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Bean
    SqlSessionTemplate sqlSessionTemplate1(){
       return new SqlSessionTemplate(sqlSessionFactory1());
    }
}
public class MybatisConfigTwo {
    @Autowired
    @Qualifier("dsTwo")
    DataSource ds2;
@Bean
    SqlSessionFactory sqlSessionFactory2(){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds2);
        try {
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Bean
    SqlSessionTemplate sqlSessionTemplate2(){
       return new SqlSessionTemplate(sqlSessionFactory2());
    }
}

  7. Test

@SpringBootTest
class MybatisApplicationTests {
    @Autowired
    UserMapper1 userMapper1;
    @Autowired
    UserMapper2 userMapper2;
    @Test
    void contextLoads() {
        List<User> users = userMapper1.getAllUser();
        System.out.println(users);
        List<User> allUser = userMapper2.getAllUser();
        System.out.println(allUser);

    }

}

  Test Results:

 

   If you want to use multiple data sources, it will be able to continue to increase, ok, you're done!

Guess you like

Origin www.cnblogs.com/hopeofthevillage/p/11774343.html