【JPA】使用JPA实现分页和模糊查询
阅读原文时间:2023年07月08日阅读:1

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

  • JpaRepository<Admin, Integer> 泛型参数分别是:要查询的实体(Entity),实体的主键类型

  • JpaSpecificationExecutor<Admin> 泛型参数:要查的实体

    @Repository
    public interface AdminRepository extends JpaRepository, JpaSpecificationExecutor {

    }

2、Service层进行查询操作

  • 创建查询条件对象

  • 创建分页对象

  • 进行查询操作

    /**
    * 分页查找Admin
    *
    * @param query 查询条件
    * @param pagenum 页码
    * @param pageSize 每页显示的数据
    * @return
    */
    @Override
    public Page 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&lt;Admin&gt; page = adminRepository.findAll(specification, pageRequest);
    
    //返回的数据都封装在了Page&lt;Admin&gt;对象中
    
    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动态构建多表查询、复杂查询及排序示例