What is the LIMIT clause alternative in JPQL?

前端 未结 7 677
不思量自难忘°
不思量自难忘° 2020-12-13 03:26

I\'m working with PostgreSQL query implementing in JPQL.

This is a sample native psql query which works fine,

SELECT * FROM students ORDER BY id DESC         


        
7条回答
  •  一向
    一向 (楼主)
    2020-12-13 04:16

    You are using JPQL which doesn't support limiting results like this. When using native JPQL you should use setMaxResults to limit the results.

    However you are using Spring Data JPA which basically makes it pretty easy to do. See here in the reference guide on how to limit results based on a query. In your case the following, find method would do exactly what you want.

    findFirstByOrderById();
    

    You could also use a Pageable argument with your query instead of a LIMIT clause.

    @Query("SELECT s FROM Students s ORDER BY s.id DESC")
    List getLastStudentDetails(Pageable pageable);
    

    Then in your calling code do something like this (as explained here in the reference guide).

    getLastStudentDetails(PageRequest.of(0,1));
    

    Both should yield the same result, without needing to resort to plain SQL.

提交回复
热议问题