When it comes to multi-data sources, what problems are generally solved? The master/slave mode or business is complex and different sub-libraries need to be connected to support business. Our project is the latter mode, online to find a lot of, mainly to do multiple source according to the jpa solution, or the old spring multiple source solution, also have a plenty of dynamic switch using aop, feel little bit complicated, in fact, I just want to find a simpler data support, sort out for two hours, for your reference.

So let’s just cut to the code

The configuration file

Pom package is not attached to the relatively simple dependence on the dependency, mainly on the database side of the configuration:

mybatis.config-locations=classpath:mybatis/mybatis-config.xml spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver spring.datasource.test1.url = jdbc:mysql://localhost:3306/test1? useUnicode=true&characterEncoding=utf-8 spring.datasource.test1.username = root spring.datasource.test1.password = root spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver spring.datasource.test2.url = jdbc:mysql://localhost:3306/test2? useUnicode=true&characterEncoding=utf-8 spring.datasource.test2.username = root spring.datasource.test2.password = rootCopy the code

Test1 library and test2 library, where test1 is the primary library, must specify the primary library during the use process, otherwise an error will be reported.

Data Source Configuration

@Configuration
@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")
public class DataSource1Config {

    @Bean(name = "test1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    @Primary
    public DataSource testDataSource(a) {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
        return bean.getObject();
    }

    @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 newSqlSessionTemplate(sqlSessionFactory); }}Copy the code

The most important part is that the DataSource is injected layer by layer, the SqlSessionFactory is created, the transaction is created, and the SqlSessionTemplate is wrapped. The mapper file address of the sub-library needs to be developed, as well as the sub-library to layer code

@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")Copy the code

This annotation indicates that the DAO layer is scanned and the dao layer is injected with the specified SqlSessionTemplate. All @beans need to be specified correctly by name.

Dao layer and XML layer

The DAO layer and XML should be placed in different directories according to libraries. For example, the TEST1 library DAO layer is stored in com.neo. Mapper. test1 and test2 library is stored in com.neo

public interface User1Mapper {

    List<UserEntity> getAll(a);

    UserEntity getOne(Long id);

    void insert(UserEntity user);

    void update(UserEntity user);

    void delete(Long id);

}Copy the code

XML layer

<?xml version="1.0" encoding="UTF-8" ? >

      
<mapper namespace="com.neo.mapper.test1.User1Mapper" >
    <resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" >
        <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="com.neo.enums.UserSexEnum"/>
        <result column="nick_name" property="nickName" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="Base_Column_List" >
        id, userName, passWord, user_sex, nick_name
    </sql>

    <select id="getAll" resultMap="BaseResultMap"  >
       SELECT 
       <include refid="Base_Column_List" />
       FROM users
    </select>

    <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
        SELECT 
       <include refid="Base_Column_List" />
       FROM users
       WHERE id = #{id}
    </select>

    <insert id="insert" parameterType="com.neo.entity.UserEntity" >
       INSERT INTO 
               users
               (userName,passWord,user_sex) 
           VALUES
               (#{userName}, #{passWord}, #{userSex})
    </insert>

    <update id="update" parameterType="com.neo.entity.UserEntity" >
       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 id="delete" parameterType="java.lang.Long" >
       DELETE FROM
                users 
       WHERE 
                id =#{id}
    </delete>

</mapper>Copy the code

test

Tests can be carried out using SpringBootTest or in the Controller, only for the Controller layer

@RestController
public class UserController {

    @Autowired
    private User1Mapper user1Mapper;

    @Autowired
    private User2Mapper user2Mapper;

    @RequestMapping("/getUsers")
    public List<UserEntity> getUsers(a) {
        List<UserEntity> users=user1Mapper.getAll();
        return users;
    }

    @RequestMapping("/getUser")
    public UserEntity getUser(Long id) {
        UserEntity user=user2Mapper.getOne(id);
        return user;
    }

    @RequestMapping("/add")
    public void save(UserEntity user) {
        user2Mapper.insert(user);
    }

    @RequestMapping(value="update")
    public void update(UserEntity user) {
        user2Mapper.update(user);
    }

    @RequestMapping(value="/delete/{id}")
    public void delete(@PathVariable("id") Long id) { user1Mapper.delete(id); }}Copy the code

The sample code


Like my article, please follow my official account