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

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

public interface StudentRepository extends JpaRepository {

  @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 findByAgeAndIdAndFirstName(Integer age, Integer id, String firstName, Pageable pageable);
}

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

你可能感兴趣的:(【后端】【Spring Boot】【JPA】使用SpringData+JPA的@Query注解完成动态条件分页查询)