【后端】【Spring Boot】【JPA】使用SpringDa

2020-08-19  本文已影响0人  普鲁托蓝

在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

上一篇 下一篇

猜你喜欢

热点阅读