SpringBoot2.0 eight multiple data source configuration

  In the process of development, we may encounter the requirements of docking with other systems of the company. For external systems, we can use interface docking. For two systems developed by one company and knowing the relevant database structure, we can consider using it. Multiple data sources to solve this problem. SpringBoot provides us with a relatively simple implementation.

1. Create a maven project with the following structure
write picture description here

2. Add relevant database configuration information

server:
  port: 8080

spring:  
  datasource:
    master:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: 123456
    slaver:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/dev?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: 123456

3. Related configuration of main library and slave library
1. Main library data source configuration

@Configuration
@MapperScan(basePackages = "com.somta.springboot.dao.master", sqlSessionTemplateRef  = "masterSqlSessionTemplate")
public class MasterDataSourceConfiguration {

    @Value("${spring.datasource.master.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.master.url}")
    private String url;

    @Value("${spring.datasource.master.username}")
    private String username;

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

    @Bean(name = "masterDataSource")
    @Primary
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        return dataSource;
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/master/**/Mysql_*Mapper.xml"));
        return bean.getObject();
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "masterSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

2. Data source configuration information from the library

@Configuration
@MapperScan(basePackages = "com.somta.springboot.dao.slaver", sqlSessionTemplateRef  = "slaverSqlSessionTemplate")
public class SlaverDataSourceConfiguration {

    @Value("${spring.datasource.slaver.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.slaver.url}")
    private String url;

    @Value("${spring.datasource.slaver.username}")
    private String username;

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


    @Bean(name = "slaverDataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        return dataSource;
    }

    @Bean(name = "slaverSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("slaverDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/slaver/**/Mysql_*Mapper.xml"));
        return bean.getObject();
    }

    @Bean(name = "slaverTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("slaverDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "slaverSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaverSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

  Note that when configuring the information of the data source, you must configure a main library through @Primary. There is no difference between the database configuration part and the ordinary data source configuration. Create a new DataSource, create a SqlSessionTemplate, and finally create a SqlSessionTemplate, respectively. That is, the scan path of the @MapperScan annotation should be respectively for the corresponding dao layer

Fourth, write dao layer and xml

public interface UserMasterDao {
    int addUser(User user);
    int deleteUserById(Long id);
    int updateUserById(User user);
    User queryUserById(Long id);
    List<User> queryUserList();
}
<?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.somta.springboot.dao.master.UserMasterDao" > 
<!-- Result Map-->
<resultMap id="BaseResultMap" type="com.somta.springboot.pojo.User" >
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="age" property="age"/>
</resultMap>

<!-- th_role_user table all fields -->
<sql id="Base_Column_List" >
    id, name, age
</sql>

<insert id="addUser" parameterType="com.somta.springboot.pojo.User" >
    insert into t_user (id, name, age) 
    values (#{id},#{name},#{age});
</insert>

<delete id="deleteUserById" parameterType="java.lang.Long">
 delete from t_user where id=#{id}
</delete>

<update id="updateUserById" parameterType="com.somta.springboot.pojo.User" >
    update t_user set 
    <trim  suffixOverrides="," >
    <if test="id != null and id != ''">
        id=#{id},
    </if>
    <if test="name != null and name != ''">
        name=#{name},
    </if>
    <if test="age != null and age != ''">
        age=#{age},
    </if>
    </trim> where id=#{id}
</update>

<select id="queryUserById" resultMap="BaseResultMap" parameterType="java.lang.Long">
    select <include refid="Base_Column_List" /> 
    from t_user where id = #{id}
</select>

<select id="queryUserList" resultMap="BaseResultMap">
    select <include refid="Base_Column_List" /> 
    from t_user
</select>

</mapper>   

5. Write test classes for testing

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class MultiDatasourceTest {
    @Autowired
    private UserMasterDao masterUserDao;
    @Autowired
    private UserSlaverDao slaverUserDao;
    /**
     * 查询用户
     * @throws Exception
     */
    @Test
    public void testQueryUser() throws Exception {
        User masterUser = masterUserDao.queryUserById(1L);
        System.out.println("masterUser==>"+masterUser.getName());

        User slaverUser = slaverUserDao.queryUserById(1L);
        System.out.println("slaverUser==>"+slaverUser.getName());
    }
}

When you see the following output in the console, it means that our configuration has been successful
write picture description here

Git code address: https://gitee.com/songhu/SpringBoot/tree/master/SpringBoot-multiDatasource

  This article was created by the horizon of tomorrow. If you want to know more and more detailed content, please pay attention to the official account. The latest and most real-time updates will be made in the official account!
QR code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325195084&siteId=291194637