What is the LIMIT clause alternative in JPQL?

Solution 1:

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<Students> 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.

Solution 2:

As stated in the comments, JPQL does not support the LIMIT keyword.

You can achieve that using the setMaxResults but if what you want is just a single item, then use the getSingleResult - it throws an exception if no item is found.

So, your query would be something like:

TypedQuery<Student> query = entityManager.createQuery("SELECT s FROM Students s ORDER BY s.id DESC", Student.class);    
query.setMaxResults(1);

If you want to set a specific start offset, use query.setFirstResult(initPosition); too

Solution 3:

Hello for fetching single row and using LIMIT in jpql we can tell the jpql if it's a native query.

( using - nativeQuery=true )

Below is the use

@Query("SELECT s FROM Students s ORDER BY s.id DESC LIMIT 1", nativeQuery=true)
Students getLastStudentDetails();

Solution 4:

You can not use Limit in HQL because Limit is database vendor dependent so Hibernate doesn't allow it through HQL query.

A way you can implement is using a subquery:

@Query("FROM Students st WHERE st.id = (SELECT max(s.id) FROM Students s)")
Students getLastStudentDetails();