jpa知识点

本文介绍了Spring Data JPA中PageRequest的使用,通过of()方法实现分页和多条件排序。示例代码展示了如何构建Pageable对象进行排序,并提供了@Query注解的countQuery用法,用于获取分页查询的总条数。同时,详细解释了countQuery必须与查询条件保持一致的原则。
摘要由CSDN通过智能技术生成

1.分页 

public static PageRequest of(int page, int size, Direction direction, String... properties) {
        return of(page, size, Sort.by(direction, properties));
    }



官方API说明: since 2.0, use of(...) instead,2.0版本后,使用 of(...) 方法代替 PageRequest(...)构造器

官方地址:https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/PageRequest.html

支持多条件排序的,比如Pageable page = PageRequest.of(1, 10, Sort.Direction.DESC, "id","name",...);

private Pageable buildPageable(Param param) {
        //param pageNo,pageSize,sortOrder,sortField
        // 添加一个名为sort的field并根据他排序,用于把负数数据始终排在最后面
        String sortField = "sort";
        Sort sort = Sort.by(Direction.ASC, sortField);
        sort = sort.and(Sort.by(Constants.ACS.equals(param.getSortOrder()) ? Direction.ASC : Direction.DESC,param.getSortField()));
        // 处理分页
        Pageable pageable= PageRequest.of(param.getPageNo() - 1, param.getPageSize(), sort);
       
        return pageable;
    }

2.@Query之countQuery

@Query(value = "select * from "
            + "(select *, 1 as sort from student_task where data_type = ?1 and value >= 0 union "
            + "select *, 2 as sort from student_task where data_type = ?1 and value < 0) A",
            countQuery = "select count(*) from "
                    + "(select *, 1 as sort from student_task where data_type = ?1 and value >= 0 union "
                    + "select *, 2 as sort from student_task where data_type = ?1 and value < 0) A",
            nativeQuery = true)
    Page<StudentTask> queryStudentTaskList(String dataType, Pageable page);

countQuery 就是分页的总条数,后面的条件需跟value的where条件保持一致。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值