今天在项目中遇到了个问题,并成功解决,记录一下,便于查阅。
背景
MyBatisplus版本:3.5.1
mapper.selectPage、service.page不生效
调查
经网上查阅,大部分说的是没有配置分页插件(3.4.3版本后用MybatisPlusInterceptor),配了后还是无效
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
于是看下MybatisPlusInterceptor源码,通过拦截方法来修改sql
于是在拦截器打断点发现,死活不进,拦截器未生效!!!
mybatis框架有问题?那是不可能的!应该还是用法问题,后来发现进了PageInterceptor,而实际没有用这个,而是用的MybatisPlusInterceptor
后查阅资料得知,mybatis的拦截器是责任链模式,在PageInterceptor这里断掉了,没有往后传递
解决方案
@Configuration
@AutoConfigureAfter(PageHelperAutoConfiguration.class)// 关键,要后扫描
public class MyBatisPageConfiguration {
@Autowired
private List<SqlSessionFactory> sqlSessionFactoryList;
@PostConstruct
public void addMyInterceptor() {
MybatisPlusInterceptor interceptor = mybatisPlusInterceptor();
for (SqlSessionFactory factory : sqlSessionFactoryList) {
factory.getConfiguration().addInterceptor(interceptor);
}
}
/**
* mybatisplus 分页拦截器
* @return
*/
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
测试
@Test
public void testPage(){
IPage<User> data = userMapper.selectPage(new Page<>(1,2),null);
log.info(JSON.toJSONString(data));
IPage<User> data1 = userService.page(new Page<>(1,2),null);
log.info(JSON.toJSONString(data1));
}