【JPA】使用JPA实现分页和模糊查询

1、首先创建DAO层接口,实现JpaRepositoryJpaSpecificationExecutor两个接口

  • JpaRepository<Admin, Integer> 泛型参数分别是:要查询的实体(Entity),实体的主键类型
  • JpaSpecificationExecutor<Admin> 泛型参数:要查的实体
@Repository
public interface AdminRepository extends JpaRepository<Admin, Integer>, JpaSpecificationExecutor<Admin> {
}

2、Service层进行查询操作

分页模糊查询三步骤:

  • 创建查询条件对象
  • 创建分页对象
  • 进行查询操作
/**
* 分页查找Admin
*
* @param query 查询条件
* @param pagenum 页码
* @param pageSize 每页显示的数据
* @return
*/
@Override
public Page<Admin> queryList(String query, Integer pagenum, Integer pageSize) {
//查询条件存在这个对象中
Specification<Admin> specification = new Specification<Admin>() {
//重新Specification的toPredicate方法
@Override
public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
//我要模糊查询的字段是adminName
Path adminName = root.get("adminName");
//criteriaBuilder.like模糊查询,第一个参数是上一行的返回值,第二个参数是like('%xxx%')中,xxx的值
Predicate predicate = criteriaBuilder.like(adminName, "%" + query + "%");
return predicate;
}
};
//分页条件存在这个对象中
PageRequest pageRequest = PageRequest.of(pagenum - 1, pageSize);
//进行查询操作,第一个参数是查询条件对象,第二个参数是分页对象
Page<Admin> page = adminRepository.findAll(specification, pageRequest);
//返回的数据都封装在了Page<Admin>对象中
return page;
}

如果要获得Page对象中的数据,可以直接使用page.getContent();方法

List<Admin> adminList = page.getContent();

Page对象中封装的数据

{
"data": {
"content": [ //查出来的数据
{
"adminId": 3,
"adminName": "b",
"adminPassword": "b",
"createTime": "2020-02-25T14:24:07.000+0000",
"isBoss": "0"
}
],
"pageable": {
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"offset": 0,
"pageNumber": 0, //页号,数据库中的第一页是从下标为0开始的
"pageSize": 2, //每页显示的条数
"paged": true,
"unpaged": false
},
"totalElements": 1, //总条数
"last": true,
"totalPages": 1, //总页数
"number": 0,
"size": 2,
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"numberOfElements": 1,
"first": true,
"empty": false
},
"code": "code",
"message": "message",
"token": "token"
}

参考博客:Spring Data JPA使用Specification动态构建多表查询、复杂查询及排序示例

posted @   周星星、同学  阅读(4089)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示