1.MybatisSqlSessionFactoryBean中添加分页插件
// 关键代码 设置 MyBatis-Plus 分页插件
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
Interceptor[] plugins = {interceptor};
factoryBean.setPlugins(plugins);
完整配置
public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource) throws Exception {
MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
factoryBean.setDataSource(dynamicDataSource);
factoryBean.setTypeAliasesPackage("com.xxx.entity");
factoryBean.setTypeAliasesPackage("com.xxx.**");
// 设置mapper.xml的位置路径
Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml");
factoryBean.setMapperLocations(resources);
factoryBean.setConfigLocation(new ClassPathResource("configuration/mybatis-config.xml"));
// 关键代码 设置 MyBatis-Plus 分页插件
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
Interceptor[] plugins = {interceptor};
factoryBean.setPlugins(plugins);
return factoryBean.getObject();
}
没有手动配置数据源时,可以使用下面简单配置
/**
* 分页插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
2.使用
Page<XXX> xxxList = xxxMapper.selectPage(
new Page<>((dto.getPageNum() - 1) * dto.getPageSize(), dto.getPageSize()),
Wrappers.lambdaQuery(XXX.class).eq(XXX::getDeleteFlag, 0)
);