在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