一、mybatis-plus分页需要借助拦截器来实现
1、定义mybatis-plus分页拦截器
package com.xiaoxu.ssmp.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PageItercepter {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
//创建mybatis-plus拦截器
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//创建mybatis-plus内部拦截器 及具体拦截操作
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());//分页拦截器
/**
* 后面需要更多的拦截操作只需要按上面添加即可
*/
return interceptor;
}
}
2、使用
@Test
public void pageQueary(){
/**
* 2 是当前页
* 3是每页显示数
* selectPage 第二个参数是查询条件
*/
Page page = new Page(2,3);
userMapper.selectPage(page,null);
}
跟踪page源码:
可以看出当前页和每页数通过构造方法传入
3、测试
二、查询返回结果中包含很对分页相关的信息
例如:总记录数 是否是第一页 最后一页等
源码:
三、条件查询时的条件封装
1、QueryWrapper
@Test
public void conditionQueary1(){
QueryWrapper<User> qw = new QueryWrapper<>();
qw.like("username","hhh");
userMapper.selectList(qw);
}
报错:
问题:User表中的字段为:
数据库的表名为:
四、为了避免手写的错误情况 所以一般采用第二种条件封装方式
采用LambdaQueryWrapper:
@Test
public void conditionQueary2(){
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
lqw.like(User::getUserName,"hhh");
userMapper.selectList(lqw);
}
五、解决前端传入的时空参数问题
如:username=null 这是万万不对的。
解决办法:再查询之前判断该属性是否为null
方法一:
可以看出没有执行like 查询
方式二:
六、实际案例
前端:
后端:
先做判断在确定是否执行。