使用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,
            "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"
}

猜你喜欢

转载自www.cnblogs.com/rxx1005/p/12364327.html