Mybatisplus分页查询
MyBatis-Plus自带分页插件,只要简单的配置即可实现分页功能
前提条件
//需要有UserMapper方法
public interface UserMapper extends BaseMapper<User> {
}
//需要有user实体类、且与数据库相对应
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
private Integer version;
}
一、创建配置类、配置分页插件
此时可以删除主类中的@MapperScan 扫描注解,加在MyConfig配置类中
//config包 --> MyConfig.java
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
二、编写分页代码
- 直接new page()对象,传入两个参数:当前页和每页显示记录数
- 调用mybatisplus方法实现分页查询
//test测试类中
@Autowired
private UserMapper userMapper;
//分页查询
@Test
public void testPage(){
//1.创建page对象。传入两个参数:当前页 和 每页显示记录数
Page<User> page = new Page(1,3);
//调用mybatisplus分页查询的方法
//调用mybatisplus分页查询过程中,底层封装
//把分页所有数据封装到page对象里面
userMapper.selectPage(page,null);//page分页中所有数据
//通过page对象获取分页数据
System.out.println(page.getCurrent()); //当前页
System.out.println(page.getRecords()); //每页数据list集合
System.out.println(page.getSize()); //每页显示记录数
System.out.println(page.getTotal()); //总记录数
System.out.println(page.getPages()); //总页数
System.out.println(page.hasNext()); //是否有下一页
System.out.println(page.hasPrevious()); //是否有上一页
}