Springboot + mybatis-plus + dy

环境

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来指定需要操作的数据库

1
2
3
4
5
less复制代码@DS("postgresql")
@Mapper
public interface CtmAskForLeaveMapper extends BaseMapper<CtmAskForLeave> {

}
1
2
3
4
5
less复制代码@DS("mysql")
@Mapper
public interface CtmThirdAskForLeaveMapper extends BaseMapper<CtmThirdAskForLeave> {

}

重写SqlSessionFactory

这步非常关键,如果不重写,可能导致分页不会返回total,以及无法使用原生BaseMapper
导致报错 Invalid bound statement (not found)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
java复制代码@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 {

1
2
3
4
5
csharp复制代码/**
* 处理数据
* @return
*/
Boolean messageAskForLeave();

}@Service
@Slf4j
public class CtmAskForLeaveServiceImpl extends ServiceImpl<CtmAskForLeaveMapper, CtmAskForLeave> implements CtmAskForLeaveService {

1
2
3
4
typescript复制代码@Override
public Boolean messageAskForLeave() {
List<CtmThirdAskForLeave> ctmThirdAskForLeaves = ctmThirdAskForLeaveMapper.selectList(null);
}

}`

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%