环境
<dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.4.1</version> </dependency><dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.1.2</version> </dependency>
配置信息
其中库为 postgresql 和 mysql ,默认postgresql为主库
配置信息如下
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl spring.datasource.dynamic.primary=postgresql spring.datasource.dynamic.strict=truespring.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<CtmThirdAskForLeave> {
}
@DS("postgresql")
@Mapper
public interface CtmAskForLeaveMapper extends BaseMapper<CtmAskForLeave> {
}
重写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<CtmAskForLeave> {
/**
* 处理数据
* @return
*/
Boolean messageAskForLeave();
}
@Service
@Slf4j
public class CtmAskForLeaveServiceImpl extends ServiceImpl<CtmAskForLeaveMapper, CtmAskForLeave> implements CtmAskForLeaveService {
@Override
public Boolean messageAskForLeave() {
List<CtmThirdAskForLeave> ctmThirdAskForLeaves = ctmThirdAskForLeaveMapper.selectList(null);
}
}