Mybatis框架的分页插件PageHelper是目前我用过的最简单的分页插件了,该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。
使用非常的简单,步骤如下:
先创建一个springboot项目,然后使用mybatis—generator来自动生成mapper和pojo
具体实现可以参考之前的一篇博客(很烂)
https://blog.csdn.net/qq_43561507/article/details/96482517
第一步:使用maven将jar抱加入到工程中
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
然后依次编写service serviceImpl controller
代码结构如下
dao entity为mybatis-generator自动生成的
service层编写如下
@Component
public interface PersonService {
public int deleteByPrimaryKey(Integer id);
public int insert(Person record);
public Person selectByPrimaryKey(Integer id);
public List<Person> selectAll();
public int updateByPrimaryKey(Person record);
public PageInfo<Person> findByPage(int pageNum, int pageSize);
}
注意最后一排 那是我们要用到的分页相关的 PageInfo是jar包提供的一个类
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
private PersonMapper personMapper;
@Override
public int deleteByPrimaryKey(Integer id) {
return personMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(Person record) {
return personMapper.insert(record);
}
@Override
public Person selectByPrimaryKey(Integer id) {
return personMapper.selectByPrimaryKey(id);
}
@Override
public List<Person> selectAll() {
return personMapper.selectAll();
}
@Override
public int updateByPrimaryKey(Person record) {
return personMapper.updateByPrimaryKey(record);
}
@Override
public PageInfo<Person> findByPage(int pageNum, int pageSize) {
//页码 页的大小
PageHelper.startPage(pageNum,pageSize);
//数据查找
List<Person> persons = personMapper.selectAll();
PageInfo<Person> pageInfo = new PageInfo<>(persons);
return pageInfo;
}
}
这是该service
最后一个方法为控制分页的
最后编写controller
@RestController
@RequestMapping("/person")
public class PersonController {
@Autowired
private PersonService personService;
@GetMapping("/findAll")
public List<Person> findAll() {
return personService.selectAll();
}
@GetMapping("/deleteById")
public int deleteByPrimaryKey(Integer id) {
return personService.deleteByPrimaryKey(id);
}
@GetMapping("/insert")
public int insert(Person person) {
return personService.insert(person);
}
@GetMapping("/select")
public Person selectByPrimaryKey(Integer id) {
return personService.selectByPrimaryKey(id);
}
@GetMapping("/update")
public int updateByPrimaryKey(Person record) {
return personService.updateByPrimaryKey(record);
}
// @GetMapping("/findByName")
// public List<Person> selectByName(String name) {
// return personService.selectByName(name);
// }
@RequestMapping("/findByPage")
public PageInfo findByPage(int pageNum){
return personService.findByPage(pageNum,3);
}
}
最后一个方法的意思是每页三条记录 手动输入你想看的页码
附上我的数据库数据
查询出所有数据
如果要分页 这样输入 http://127.0.0.1:8080/person/findByPage?pageNum=1
查询第一页 三条数据
分页查询成功