Spring JPA分页查询

在项目中分页查询是一个很常见的场景,通过JPA可以简单的实现分页功能。

首先创建一个接口类,继承 JpaRepository接口。JpaRepository接口中已经继承了分页和排序所需的相关接口PagingAndSortingRepository接口和基本的查询接口QueryByExampleExecutor。

还是以之前的学生类为模板。JpaRepository中第一个类型为数据库映射对应的实体,第二个为数据库表中主键的类型。

public interface StudentJpaRepository extends JpaRepository<StudentEntity, String> {
    
}

我们想用实现分页查询如下:

@Resource
public class StudentServiceImpl {
    private final StudentJpaRepository studentJpaRepository;

    public StudentServiceImpl(StudentJpaRepository studentJpaRepository) {
        this.studentJpaRepository = studentJpaRepository;
    }

    public List<StudentEntity> queryPage() {
        Page<StudentEntity> page = studentJpaRepository.findAll(PageRequest.of(1, 20));
        return page.toList();
    }
}

需要注意的是分页查询的起始页签为0,如果需要根据某些字段进行排序的话需要传入Sort类。例如我们需要根据学号进行升序排序的话,可以按照如下方式实现。

@Resource
public class StudentServiceImpl {
    private final StudentJpaRepository studentJpaRepository;

    public StudentServiceImpl(StudentJpaRepository studentJpaRepository) {
        this.studentJpaRepository = studentJpaRepository;
    }

    public List<StudentEntity> queryPage() {
        Sort.TypedSort<StudentEntity> typedSort = Sort.sort(StudentEntity.class);
        Sort ascending = typedSort.by(StudentEntity::getStudentId).ascending();

        Page<StudentEntity> page = studentJpaRepository.findAll(PageRequest.of(1, 20, ascending));
        return page.toList();
    }
}

简单的查询就不进行赘述了,实现起来是不是感觉简单很多,而且自动映射为相关的对象,直接就可以进行使用。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值