spring.shardingsphere + mybatis plus 配置多数据源

1.引入依赖


    org.apache.shardingsphere
    sharding-jdbc-spring-boot-starter
    ${sharding.jdbc.spring}


    org.apache.shardingsphere
    sharding-jdbc-spring-namespace
    ${sharding.jdbc.spring}


    com.baomidou
    mybatis-plus-boot-starter
    3.4.3.4

2.yaml配置

spring:
  shardingsphere:
    datasource:
      names: ds0,ds1
      ds0:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://192.168.4.163:3306/dsp?characterEncoding=utf-8&useOldAliasMetadataBehavior=true&allowMultiQueries=true&useAffectedRows=true&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=Asia/Shanghai
        username: ***
        password: ***
      ds1:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://192.168.4.163:3306/cujia-payment?characterEncoding=utf-8&useOldAliasMetadataBehavior=true&allowMultiQueries=true&useAffectedRows=true&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=Asia/Shanghai
        username: ***
        password: ****

3.数据源bean配置

@Configuration
public class DataSourceConfig {

    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.shardingsphere.datasource.ds0")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

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

4.配置sqlsessionFactory

@Configuration
@MapperScan(basePackages = "me.mason.demo.basicmultidatasource.mapper.master", sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterMybatisConfig {
    /**
     * 注意,此处需要使用MybatisSqlSessionFactoryBean,不是SqlSessionFactoryBean,
     * 否则,使用mybatis-plus的内置函数时就会报invalid bound statement (not found)异常
     */
    @Bean("masterSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        // 设置数据源
        MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        mybatisSqlSessionFactoryBean.setDataSource(dataSource);
        //mapper的xml文件位置
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String locationPattern = "classpath*:/mapper/master/*.xml";
        mybatisSqlSessionFactoryBean.setMapperLocations(resolver.getResources(locationPattern));
        //对应数据库的entity位置
        String typeAliasesPackage = "me.mason.demo.basicmultidatasource.entity.master";
        mybatisSqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        return mybatisSqlSessionFactoryBean.getObject();
    }
}
@Configuration
@MapperScan(basePackages = "me.mason.demo.basicmultidatasource.mapper.slave", sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class SlaveMybatisConfig {
    /**
     * 注意,此处需要使用MybatisSqlSessionFactoryBean,不是SqlSessionFactoryBean,
     * 否则,使用mybatis-plus的内置函数时就会报invalid bound statement (not found)异常
     */
    @Bean("slaveSqlSessionFactory")
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
        // 设置数据源
        MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        mybatisSqlSessionFactoryBean.setDataSource(dataSource);
        //mapper的xml文件位置
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String locationPattern = "classpath*:/mapper/slave/*.xml";
        mybatisSqlSessionFactoryBean.setMapperLocations(resolver.getResources(locationPattern));
        //对应数据库的entity位置
        String typeAliasesPackage = "me.mason.demo.basicmultidatasource.entity.slave";
        mybatisSqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        return mybatisSqlSessionFactoryBean.getObject();
    }
}

5.实体类

@Data
@TableName("test_user")
public class MasterTestUser implements Serializable {
    private static final long serialVersionUID = 1L;
    /** id */
    private Long id;
    /** 姓名 */
    private String name;
    ...
}

6.mapper

@Repository
public interface MasterTestUserMapper extends BaseMapper {
    /**
     * 自定义查询
     * @param wrapper 条件构造器
     */
    List selectAll(@Param(Constants.WRAPPER)Wrapper wrapper);
}

7.xml


    

8.使用

@RestController
@RequestMapping("/user")
public class TestUserController {

    @Autowired
    private MasterTestUserMapper masterTestUserMapper;
    @Autowired
    private SlaveTestUserMapper slaveTestUserMapper;
    /**
     * 查询全部
     */
    @GetMapping("/listall")
    public Object listAll() {
        //master库,自定义接口查询
        QueryWrapper queryWrapper = new QueryWrapper<>();
        List resultData = masterTestUserMapper.selectAll(queryWrapper.isNotNull("name"));
        //slave库,mp内置接口
        List resultDataSlave = slaveTestUserMapper.selectList(null);
        //返回
        Map result = new HashMap<>();
        result.put("master" , resultData);
        result.put("slave" , resultDataSlave);
        return ResponseResult.success(result);
    }

}

参考:

https://blog.csdn.net/weixin_43819744/article/details/122809553

SpringBoot多数据源_Kesling的博客-CSDN博客_springboot 多数据源

你可能感兴趣的:(java,spring,mybatis,java)