在springboot中使用mybatis-plus的分页功能
一、测试分页功能:
编写测试代码:
@Test
public void testPage(){
//设置分页参数,页码为1,大小为5
Page<Employee> page = new Page<>(1, 5);
//传入page对象,条件构造为null
employeeMapper.selectPage(page, null);
//获取分页数据
List<Employee> list = page.getRecords();
//输出分页数据
list.forEach(System.out::println);
System.out.println("当前页:"+page.getCurrent());
System.out.println("每页显示的条数:"+page.getSize());
System.out.println("总记录数:"+page.getTotal());
System.out.println("总页数:"+page.getPages());
System.out.println("是否有上一页:"+page.hasPrevious());
System.out.println("是否有下一页:"+page.hasNext());
}
可以看到,很轻松的实现了分页功能。
二、实际使用场景:
1、编写一个mybatis-plus配置类:
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
// MyBatis Plus分页插件
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
2、编写mapper接口:
注:(实体类代码不再给出,请自己添加)
@Mapper
public interface EmployeeMapper extends BaseMapper<Employee> {
}
3、编写Controller层后端接口:
@RestController
@RequestMapping("/emp")
public class EmployeeController {
@Autowired
private EmployeeMapper employeeMapper;
@GetMapping("/getEmpByPage/{page}/{size}")
public Page<Employee> getPage(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
//设置分页参数
Page<Employee> pageable = new Page<>(page, size);
Page<Employee> employeePage = employeeMapper.selectPage(pageable, null);
return employeePage;
}
}
4、测试接口:
访问:http://localhost:8000/emp/getByPage/1/3
这里我选择访问的是第1页的3条记录: