Proficiency in SpringBoot - Article 13: Integrating Mybatis Multiple Data Sources

Keywords: Java Spring MySQL Mybatis

Long time no see, recently passed a period of burnout, this period of time do not have motivation, procrastination recurrence. Fortunately, I'm back... - From me.
Getting into today's topic, integrating mybatis multiple data sources in Spring Book project, is actually simple, but not difficult.
Overall project structure and data source configuration application.yml:

Look at the code.

First data source configuration (as master data source)

/**
 * @author Lensen
 * @desc
 * @since 2018/9/19 10:22
 */
@Configuration
@MapperScan(basePackages = PrimaryDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {
    static final String PACKAGE = "com.developlee.multipartmybatisdatasource.dao.primary";
    static final String MAPPER_LOCATION = "classpath:mapper/primary/*.xml";
    @Value("${primary.datasource.url}")
    private String url;

    @Value("${primary.datasource.username}")
    private String user;

    @Value("${primary.datasource.password}")
    private String password;

    @Value("${primary.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "primaryDataSource")
    @Primary
    public DataSource primaryDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

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

    @Bean(name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(primaryDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(PrimaryDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

Second Data Source Configuration



/**
 * @author Lensen
 * @desc
 * @since 2018/9/19 10:22
 */
@Configuration
@MapperScan(basePackages = SecondaryDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondaryDataSourceConfig {
    static final String PACKAGE = "com.developlee.multipartmybatisdatasource.dao.secondary";
    static final String MAPPER_LOCATION = "classpath:mapper/secondary/*.xml";
    @Value("${secondary.datasource.url}")
    private String url;

    @Value("${secondary.datasource.username}")
    private String user;

    @Value("${secondary.datasource.password}")
    private String password;

    @Value("${secondary.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "secondaryDataSource")
    public DataSource secondaryDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

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

    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(secondaryDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(SecondaryDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

}

Other business logic codes are not pasted, and the code can be found on my github. There is an address at the end of the article.

application.yml


## primary data source configuration
primary:
  datasource:
    url: jdbc:mysql://localhost:3306/javashop?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver

## secondary data source configuration
secondary:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver

pom.xml

     <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>1.3.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>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

Test:


@RunWith(SpringRunner.class)
@SpringBootTest
public class MultipartMybatisDatasourceApplicationTests {

    @Autowired
    UserServiceImpl userService;
    @Autowired
    HomeServiceImpl homeService;
    @Test
    public void contextLoads() {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(1L);
        userEntity.setName("Lensen");
        userEntity.setMobile("13738718660");
        HomeEntity homeEntity = new HomeEntity();
        homeEntity.setId(1L);
        homeEntity.setUserId(1L);
        homeEntity.setCity("Hangzhou");
        homeEntity.setTown("xihu district");

         userService.saveUser(userEntity);
         homeService.saveHome(homeEntity);

         userService.getUserById(1L);
         homeService.getHomeByUserId(1L);
    }

}

Code can be in my github.com Found in.

That's All. Paying attention to my public number will not necessarily update the article. hahah~~

Posted by Jeroen_nld on Sun, 27 Jan 2019 03:42:14 -0800