前言
学习数据库很久了,并且对于CRUD(增、删、改、查)已经烂熟于心了,相信许多跟我一样还天天对于数据库的操作仅限于此的朋友们一定早已感到枯燥了,那么我们赶紧进入话题,来谈谈分页查询的使用吧!
(基本上是第一次写博客,有错的或是言语不当的地方还望多多指教,在此跪拜了)
什么是分页查询
分页查询,就是将过多的结果再有限的页面上分好多页来显示,这是许多网站常用的功能,也是最基本的功能。
分页查询的应用
这里我们使用的是 SpringBoot 中 JPA 的分页查询
首先引入JPA的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Repository层
import com.Model.UserInfo;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface SourceCodeDao extends PagingAndSortingRepository<UserInfo, Integer> {}
该接口继承了PagingAndSortingRepository中的方法
Service层
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import com.Model.UserInfo;
import com.Repository.SourceCodeDao;
public Page<UserInfo> getSourceCode(int pageNumber, int pageSize){
PageRequest request = this.buildPageRequest(pageNumber,pageSize);
Page<UserInfo> sourceCodes = this.sourceCodeDao.findAll(request);
return sourceCodes;
}
private PageRequest buildPageRequest(int pageNumber, int pagzSize) {
return new PageRequest(pageNumber - 1, pagzSize, null);
}
getSourceCode()方法传入两个参数,pageNumber为页码的当前页,pageSize为每一页显示的条数,该方法返回值为一个Page类型(UserInfo是每条信息对应的实体类)
PageRequest()中传入三个参数,前两个参照上面,注意第一个参数需要减一,因为分页的当前页是从0开始算起,最后一个参数为排序属性,可以设置为按照自己想要的方式进行排序,因为我这里分页查出来后的数据不涉及到排序,所以这里排序我直接传入null。
Controller层
import org.springframework.data.domain.Page;
import net.sf.json.JSONArray;
Page<UserInfo> sourceCodes = this.sourceCodeService.getSourceCode(pageNow, rows);
JSONArray jsonArray = JSONArray.fromObject(sourceCodes.getContent().toArray());
我最后的分页结果我转换成了JsonArray格式传给了前台,然后前台遍历显示在页面上
总结
这次因为项目中需要使用分页,于是百度查询了下分页的使用,成功运行后在此简单的记录下也希望能帮到更多的人。