Springboot + mybatis-plus + dynamic-datasource-spring-boot-starter整合多数据源

环境


    com.baomidou
    dynamic-datasource-spring-boot-starter
    3.4.1

    com.baomidou
    mybatis-plus
    3.1.2

配置信息

其中库为  postgresql  和 mysql ,默认postgresql为主库

配置信息如下

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
spring.datasource.dynamic.primary=postgresql
spring.datasource.dynamic.strict=true
spring.datasource.dynamic.datasource.mysql.url=jdbc:mysql://localhost:3306/spring_boot_test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false
spring.datasource.dynamic.datasource.mysql.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.mysql.username=root
spring.datasource.dynamic.datasource.mysql.password=123456

spring.datasource.dynamic.datasource.postgresql.url=jdbc:postgresql://localhost:7092/postgres
spring.datasource.dynamic.datasource.postgresql.driver-class-name=org.postgresql.Driver
spring.datasource.dynamic.datasource.postgresql.username=postgres
spring.datasource.dynamic.datasource.postgresql.password=123456

mapper文件 

利用DS来指定需要操作的数据库

@DS("mysql")
@Mapper
public interface CtmThirdAskForLeaveMapper extends BaseMapper {

}
@DS("postgresql")
@Mapper
public interface CtmAskForLeaveMapper extends BaseMapper {

}

重写SqlSessionFactory

这步非常关键,如果不重写,可能导致分页不会返回total,以及无法使用原生BaseMapper

导致报错 Invalid bound statement (not found)

@Configuration
@MapperScan("mappper所在包")
public class MybatisPlusConfig {


    /**
     * 分页插件*/
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*/*.xml"));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{paginationInterceptor()});
        return sqlSessionFactoryBean.getObject();
    }

    
}

测试代码

public interface CtmAskForLeaveService extends IService {


    /**
     * 处理数据
     * @return
     */
    Boolean messageAskForLeave();

}
@Service
@Slf4j
public class CtmAskForLeaveServiceImpl extends ServiceImpl implements CtmAskForLeaveService {

    @Override
    public Boolean messageAskForLeave() {
        List ctmThirdAskForLeaves = ctmThirdAskForLeaveMapper.selectList(null);
    }
}

你可能感兴趣的:(SpringBoot,spring,boot,spring,java,mybaties-plus,dynamic)