SoFunction
Updated on 2025-03-04

Detailed explanation of SpringBoot's example implementation of multi-data source configuration

Configuration File

The Pom package is not posted, and it is relatively simple. It depends on the configuration of the database:

-location=classpath:mybatis/
 
.-url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
.=root
.=root
.-class-name=
 
.-url=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
.=root
.=root
.-class-name=

A test1 library and a test2 library, where the test1 bit main library must be specified during use, otherwise an error will be reported.

Data source configuration

@Configuration
@MapperScan(basePackages = ".test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")
public class DataSource1Config {
 
    @Bean(name = "test1DataSource")
    @ConfigurationProperties(prefix = ".test1")
    @Primary
    public DataSource testDataSource() {
        return ().build();
 
    }
 
    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        (dataSource);
        (new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
        return ();
    }
 
    @Bean(name = "test1TransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
 
    @Bean(name = "test1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

This is the most critical part. Inject layer by layer. First create a DataSource, then create a SqlSessionFactory and then create a transaction, and finally wrap it in SqlSessionTemplate. It is necessary to specify the mapper file address of the sub-repository and the sub-repository layer code.

@MapperScan(basePackages = ".test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")

The annotation in this section specifies the scanning layer and injects the specified SqlSessionTemplate into the layer. All @Beans need to be specified correctly by naming.

dao layer and xml layer

The dao layer and xml need to be divided into different directories according to the library, such as: the dao layer of the test1 library is under the .test1 package, and the test2 library is in .test2

public interface User1Mapper {
 
    List<UserEntity> getAll();
 
    UserEntity getOne(Long id);
 
    void insert(UserEntity user);
 
    void update(UserEntity user);
 
    void delete(Long id);
 
}

xml layer

<mapper namespace=".test1.User1Mapper" >
    <resultMap  type="" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="userName" property="userName" jdbcType="VARCHAR" />
        <result column="passWord" property="passWord" jdbcType="VARCHAR" />
        <result column="user_sex" property="userSex" javaType=""/>
        <result column="nick_name" property="nickName" jdbcType="VARCHAR" />
    </resultMap>
 
    <sql  >
        id, userName, passWord, user_sex, nick_name
    </sql>
 
    <select  resultMap="BaseResultMap"  >
       SELECT 
       <include ref />
     FROM users
    </select>
 
    <select  parameterType="" resultMap="BaseResultMap" >
        SELECT 
       <include ref />
     FROM users
     WHERE id = #{id}
    </select>
 
    <insert  parameterType="" >
       INSERT INTO 
          users
          (userName,passWord,user_sex) 
        VALUES
          (#{userName}, #{passWord}, #{userSex})
    </insert>
 
    <update  parameterType="" >
       UPDATE 
          users 
       SET 
        <if test="userName != null">userName = #{userName},</if>
        <if test="passWord != null">passWord = #{passWord},</if>
        nick_name = #{nickName}
       WHERE 
          id = #{id}
    </update>
 
    <delete  parameterType="" >
       DELETE FROM
           users 
       WHERE 
           id =#{id}
    </delete>
 
</mapper>

test

The test can be done using SpringBootTest or placed in the Controller. Only the use of the Controller layer is posted here.

@RestController
public class UserController {
 
    @Autowired
    private User1Mapper user1Mapper;
 
    @Autowired
    private User2Mapper user2Mapper;
 
    @RequestMapping("/getUsers")
    public List<UserEntity> getUsers() {
        List<UserEntity> users=();
        return users;
    }
 
    @RequestMapping("/getUser")
    public UserEntity getUser(Long id) {
        UserEntity user=(id);
        return user;
    }
 
    @RequestMapping("/add")
    public void save(UserEntity user) {
        (user);
    }
 
    @RequestMapping(value="update")
    public void update(UserEntity user) {
        (user);
    }
 
    @RequestMapping(value="/delete/{id}"
    public void delete(@PathVariable("id") Long id) {
        (id);
    }
 
}

The Mybatis annotation version configuration is basically the same as the Xml version.

The above is a detailed explanation of the examples of SpringBoot implementing multi-data source configuration. For more information about SpringBoot multi-data source configuration, please pay attention to my other related articles!