【后端】【Spring Boot】【JPA】使用SpringData+JPA的@Query注解完成动态条件分页查询

在Repository中使用@Query注解进行分页查询。

public interface StudentRepository extends JpaRepository<Student,Integer> {

  @Query(
      value = "SELECT * FROM student"
          + " WHERE (age = ?1 OR ?1 IS NULL)"
          + " WHERE (id = ?2 OR ?2 IS NULL)"
          + " WHERE (first_name = ?3 OR ?3 IS NULL)"
          + " ORDER BY ?#{#pageable}", 
      countQuery = "SELECT COUNT(1) FROM "
          + "SELECT * FROM student"
          + " WHERE (age = ?1 OR ?1 IS NULL)"
          + " WHERE (id = ?2 OR ?2 IS NULL)"
          + " WHERE (first_name = ?3 OR ?3 IS NULL)"
          + " ORDER BY ?#{#pageable}",
      nativeQuery = true
  )
  Page<Student> findByAgeAndIdAndFirstName(Integer age, Integer id, String firstName, Pageable pageable);
}

最后的Pageable可以使用PageRequest来创建。
参考:
https://segmentfault.com/a/1190000019782020?utm_source=tag-newest

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。