Spring Data JPA 之分页查询

JPA分页查询实战
本文详细介绍如何在Java项目中利用JPA进行高效分页查询,包括实体类、DAO、接口和服务层的具体实现,以及参数处理和异常抛出的注意事项。

JPA的分页查询确实使用起来确实很简单,但理解起来有点困难,此处只是实现JPA分页的代码块。

定义实体类:

@Entity
@Table(name = "t_pub_info")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class InfoPO implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
	
    @Column(name ="name")
    private String name;

    @Column(name = "priority")
    private String priority;

    @Column(name = "pub_time")
    private Date pubTime;

    @Column(name = "depict")
    private String depict;
	
	@Column(name ="city_id")
	private Long cityId;

    @Column(name = "status")
    private String status;

    Getter...
    Setter...
}

定义DAO:

public interface InfoDao extends JpaRepository<InfoPO, Long>, JpaSpecificationExecutor<InfoPO> {

}

定义接口:

@SuppressWarnings(value = "unused")
@RestController
@RequestMapping(value = "/info")
public class InfoController {
	
    @Autowired
    InfoService infoService;

    @GetMapping(value = "/list")
    Object queryInfoList(@RequestParam(value = "pageNo", required = false, defaultValue = "0") Integer pageNo,
                          @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize,
                          @RequestParam(value = "status", required = false) String status,
                          @RequestParam(value = "priority", required = false) String priority,
                          @RequestHeader("city_id")Integer cityId) {
        return infoService.queryInfoList(pageNo, pageSize, priority,cityId,String status);
    }
}

定义service

public interface InfoService {
    Object queryinfoList(Integer pageNo, Integer pageSize, String priority,Integer cityId,String status);
}

实现service

@Service
public class InfoServiceImpl implements InfoService {
    protected static final int PAGE_SIZE = 5;

    @Autowired
    InfoDao infoDao;

    public Object queryInfoList(Integer pageNo, Integer pageSize, String priority,Integer cityId,String status) {

        //验证city_id
        if(cityId == null){
            throw new Exception("city id necessary");
        }

        Integer currentPage = pageNo  == null ? 0 : pageNo;

        Page<InfoPO> page = infoDao.findAll((Root<InfoPO> root, CriteriaQuery<?> cq, CriteriaBuilder cb) -> {
            //添加分页筛选条件
            List<Predicate> predicates = new ArrayList<>();
            if (priority != null) {
                predicates.add(cb.equal(root.get("priority"), priority));
            }
            if (status != null) {
                String statusName = status;
                if (StringUtils.isNotBlank(statusName)) {
                    predicates.add(cb.equal(root.get("status"), statusName));
                }
            }

            if (cityId != null) {
                predicates.add(cb.equal(root.get("cityId"), cityId));
            }

            return cb.and(predicates.toArray(new Predicate[]{}));
        }, new PageRequest(currentPage, pageSize, new Sort(Sort.Direction.DESC, "pubTime")));
        
		//获取页面数据以及分页数据
		List<InfoPO> infos = page.getContent();
        Integer totalPage = page.getTotalPages();
        Long totalElement = page.getTotalElements();
       
        return infos;
    }
}

 github上有我更多的笔记:Raray-chuan (兮川) · GitHub,欢迎stars与following,如果有问题可以在issue中向我咨询

关注我的公众号,获取更多关于后端、大数据的知识

### 如何使用 Spring Data JPA 实现分页查询 Spring Data JPA 提供了一种简单而强大的机制来实现数据的分页查询。以下是关于其工作原理和具体使用的详细介绍。 #### 使用 `Page` 和 `Pageable` 进行分页查询Spring Data JPA 中,可以通过定义 Repository 方法并传递 `Pageable` 对象来进行分页操作。`Pageable` 是一个接口,用于描述分页请求中的页面索引、页面大小和其他属性。返回结果通常是一个 `Page<T>` 类型的对象,它不仅包含了当前页的数据集合,还提供了有关总记录数、总页数以及其他元信息的方法[^1]。 下面展示了一个典型的例子: ```java import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { // 定义支持分页的自定义查询方法 Page<User> findByStatus(String status, Pageable pageable); } ``` 在这个例子中,`findByStatus` 方法接受两个参数:一个是过滤条件(如状态),另一个是 `Pageable` 参数用来指定分页细节。调用此方法时可以传入具体的分页配置[^3]。 #### 创建 `Pageable` 实例 为了创建一个 `Pageable` 实例,最常用的方式就是利用 `PageRequest.of()` 静态工厂方法。该方法允许开发者设置起始页码(从零开始)、每页显示条目数目以及可选的排序规则[^4]。 示例如下: ```java import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; // 基础分页无排序 Pageable pageable = PageRequest.of(pageNumber, pageSize); // 添加升序排序 Pageable sortedByAsc = PageRequest.of(pageNumber, pageSize, Sort.by(Sort.Direction.ASC, "name")); // 复杂多字段排序 Pageable complexSort = PageRequest.of( pageNumber, pageSize, Sort.by(Sort.Order.asc("lastName"), Sort.Order.desc("firstName")) ); ``` 上述代码片段展示了三种不同类型的 `Pageable` 构造方式,分别对应于基本分页需求、单字段排序需求以及涉及多个字段复杂排序的需求。 #### 调用服务层完成最终查询逻辑 当 Repository 层已经准备好之后,在 Service 或 Controller 层就可以轻松地发起带有分页特性的数据库检索命令了。比如在一个 RESTful API 的场景里,可能像这样编写控制器代码: ```java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{pageNumber}/{pageSize}") public ResponseEntity<Page<User>> getUsers(@PathVariable int pageNumber, @PathVariable int pageSize){ Pageable paging = PageRequest.of(pageNumber - 1, pageSize); // 注意前端一般是从第一页即1开始计数 Page<User> pagedResult = userService.findAllUsers(paging); if (pagedResult.hasContent()) { return new ResponseEntity<>(pagedResult, HttpStatus.OK); } else{ return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } } ``` 这里需要注意的是,由于 HTTP 请求路径变量通常是基于人类习惯设定的第一页为编号 “1”,而在内部计算过程中则需转换成以零为基础的位置表示形式。 --- ### 总结 通过以上介绍可以看出,借助 Spring Data JPA 可以非常方便快捷地构建出具备强大功能的应用程序组件,尤其是针对大数据量情况下的高效管理方案更是不可或缺的一部分[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值