SpringBoot 2.0 | SpringBoot + MyBatis Configure Multiple Data Sources

In the traditional monolithic architecture, one system corresponds to one database, but in a distributed system, such as micro-services, each service corresponds to one database. Due to business requirements, sometimes it is necessary to access data from multiple databases in one service. We need to configure multiple data sources. The following are the parties that configure multiple data sources in SpringBoot 2.0.5 + MyBatis +.yml formatMethod.

Data Source Configuration

Configuration of application.yml file

spring:
  datasource:
    article-service:
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: roof
      jdbc-url: jdbc:mysql://localhost:3306/articleservice?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true

    video-service:
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: roof
      jdbc-url: jdbc:mysql://localhost:3306/videoservice?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true

# port settings
server:
  port: 8083

In a single data source configuration, the database address is written in

url: jdbc:mysql://localhost:3306

In multiple data sources, you need to precede the url with jdbc-

 jdbc-url: jdbc:mysql://localhost:3306

Configuration of data sources

Create multiple configuration classes, each corresponding to the configuration of a data source. The following is the configuration of a data source.

@Configuration
//Configure mbatis interface
@MapperScan(basePackages = "com.hly.springbootmybatismultidatasources.dao.ArticleService", sqlSessionFactoryRef = "articleServiceSqlSessionFactory")
public class ArticleServiceDataSourceConfig {

    //Place objects in containers
    @Bean(name = "articleServiceDataSource")
    //Represents the default data source
    @Primary
    //Objects configured by yml
    @ConfigurationProperties(prefix = "spring.datasource.article-service")
    public DataSource getArticleServiceDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "articleServiceSqlSessionFactory")
    @Primary
    //@Qualifier looks for an object named articleServiceDataSource in the Spring container
    public SqlSessionFactory articleServiceSqlSessionFactory(@Qualifier("articleServiceDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //Configure the location of the Mybatis XML file
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/articleService/*.xml"));
        return bean.getObject();
    }
    @Bean(name = "articleServiceSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate articleServiceSqlSessionTemplate(@Qualifier("articleServiceSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

Mapper & Dao

Mapper and Dao for each data source are distinguished by different directories

test

data base

DROP TABLE IF EXISTS `video`;
CREATE TABLE `video`(
  `v_id` int(11) NOT NULL AUTO_INCREMENT,
  `v_name` varchar(20) NOT NULL DEFAULT '',
  `a_id` int(11) NOT NULL,
  PRIMARY KEY (`v_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 DEFAULT CHARSET=utf8


DROP TABLE IF EXISTS `article`;
CREATE TABLE `article`(
  `a_id` int(11) NOT NULL AUTO_INCREMENT,
  `a_name` varchar(20) NOT NULL DEFAULT '',
  PRIMARY KEY (`a_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 DEFAULT CHARSET=utf8

Mapper.xml file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hly.springbootmybatismultidatasources.dao.ArticleService.ArticleDao">

    <resultMap id="articleResult" type="com.hly.springbootmybatismultidatasources.entity.Article">
        <id column="a_id" property="a_id"/>
        <result column="a_name" property="a_name"/>
    </resultMap>

    <select id="getArticles" resultMap="articleResult">
        SELECT * FROM article;
    </select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hly.springbootmybatismultidatasources.dao.VideoService.VideoDao">

    <resultMap id="videoResultMap" type="com.hly.springbootmybatismultidatasources.entity.Video">
        <id column="v_id" property="v_id"/>
        <result column="v_name" property="v_name"/>
        <result column="a_name" property="a_name"/>
    </resultMap>

    <select id="getVideoByArticleId" parameterType="integer" resultMap="videoResultMap">
        SELECT * FROM video
        <if test="a_id!=null">
            WHERE a_id = #{a_id}
        </if>
    </select>
</mapper>

Dao interface

@Repository
public interface ArticleDao {
    List<Article> getArticles();
}
@Repository
public interface VideoDao {
    List<Video> getVideoByArticleId(@Param(value="a_id")int  a_id);
}

Controller

@RestController
public class TestController {

    @Autowired
    ArticleDao articleDao;

    @Autowired
    VideoDao videoDao;

    @RequestMapping(value = "/articles")
    public Object getArticle(){
        return articleDao.getArticles();
    }

    @RequestMapping(value = "/videos")
    public Object getVideoByArticleId(int a_id){
        return videoDao.getVideoByArticleId(a_id);
    }
}

My Github: Github
Personal website: Sirius Blog
Source download: SpringBoot + MyBatis Configure Multiple Data Sources

Keywords: JDBC Mybatis MySQL xml

Added by staffanolin on Sun, 01 Dec 2019 21:25:50 +0200