转载

SpringBoot配置Mybatis多数据源

SpringBoot配置Mybatis多数据源
项目结构

3. 多数据源配置

application.yml 配置如下:

spring:
  application:
    name: lab-test
  datasource:
    primary:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/laboratory
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: root
    secondary:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/test
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: root
mybatis:
  type-aliases-package: cn.ntshare.laboratory.domain
  configuration:
    map-underscore-to-camel-case: true
复制代码

注意:使用 jdbc-url 属性代替之前配置中的 url 属性

mybatis中的配置中也不再写xml文件的位置,这个位置会在后面的具体数据源中进行配置

创建一个Spring配置类,定义两个DataSource来读取application.yml中的不同配置,在上述yaml中,spring.datasource.primary为主数据源配置,spring.datasource.secondary为第二数据源配置,代码如下:

@Configuration
public class DataSourceConfig {

    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix="spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

}

复制代码

4. 配置数据源

4.1 增加对第一数据源的配置

注意其中指定数据源对应的 mapper 文件定义位置和 xml 文件定义位置,用 @Primary 来区分主数据源,代码如下:

@Configuration
@MapperScan(basePackages = "cn.ntshare.laboratory.mapper.master", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimarySourceConfig {

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Bean(name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(primaryDataSource);       // 使用主数据源
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/master/*.xml"));     // 配置xml文件位置
        return factoryBean.getObject();
    }

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

    @Bean(name = "primarySqlSessionTemplate")
    @Primary
    public SqlSessionTemplate primarySqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(primarySqlSessionFactory());
    }

}

复制代码

4.2 增加第二数据源的配置

第二数据源的配置与第一数据源配置类似,代码如下:

@Configuration
@MapperScan(basePackages = {"cn.ntshare.laboratory.mapper.slave"}, sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondarySourceConfig {

    @Autowired
    @Qualifier("secondaryDataSource")
    private DataSource secondaryDataSource;

    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(secondaryDataSource);       // 使用次数据源
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/slave/*.xml"));
        return factoryBean.getObject();
    }

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

    @Bean(name = "secondarySqlSessionTemplate")
    public SqlSessionTemplate secondarySqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(secondarySqlSessionFactory());
    }

}
复制代码

完成上述配置之后

主数据源Dao层文件的位置为: cn.ntshare.laboratory.mapper.master 主数据源xml文件的位置为: classpath:mybatis/mapper/master/

次数据源Dao层文件的位置为: cn.ntshare.laboratory.mapper.slave 次数据源xml文件的位置为: classpath:mybatis/mapper/master/

可参照上文中的项目结构

5. 新Mapper文件和xml文件

主数据源下创建 MUserMappper.javaMUserMapper.xml

@Repository
@Mapper
public interface MUserMapper {

    List<MUser> selectAll();
}
复制代码
<?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="cn.ntshare.laboratory.mapper.master.MUserMapper">
    <select id="selectAll" resultType="cn.ntshare.laboratory.domain.MUser">
        select * from m_user
    </select>
</mapper>
复制代码

次数据源下创建 SUserMappper.javaSUserMapper.xml

@Repository
@Mapper
public interface SUserMapper {

    List<SUser> selectAll();
}

复制代码
<?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="cn.ntshare.laboratory.mapper.slave.SUserMapper">
    <select id="selectAll" resultType="cn.ntshare.laboratory.domain.SUser">
        select * from s_user
    </select>
</mapper>
复制代码

通过这样的配置,使用MUserMapper就可以操作主数据库,使用SUserMapper就可以操作从数据库中的数据。

6. 测试

6.1 数据源

数据库laboratory中有数据表m_user,如图:

SpringBoot配置Mybatis多数据源

数据库test中有数据表s_user,如图:

SpringBoot配置Mybatis多数据源

6.2 单元测试

MUserMapperTest

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class MUserMapperTest {

    @Autowired
    private MUserMapper mUserMapper;

    @Test
    public void testSelectAll() {
        List<MUser> users = mUserMapper.selectAll();
        users.forEach(e -> System.out.println(e.getUsername()));
    }
}
复制代码

运行结果:

SpringBoot配置Mybatis多数据源

SUserMapperTest

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class SUserMapperTest {

    @Autowired
    private SUserMapper sUserMapper;

    @Test
    public void testSelectAll() {
        List<SUser> users = sUserMapper.selectAll();
        users.forEach(e -> System.out.println(e.getUsername()));
    }
}
复制代码

运行结果:

SpringBoot配置Mybatis多数据源

多数据源环境搭建完成

原文  https://juejin.im/post/5d11928ef265da1bbf692aa3
正文到此结束
Loading...