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 LIMIT 1;
The same query in JPQL doesnt work,
@Query("SELECT s FROM Students s ORDER BY s.id DESC LIMIT 1")
Students getLastStudentDetails();
seems like LIMIT clause doesn't work in JPQL.
According to JPA documentation we can use setMaxResults/setFirstResult
, Can anyone tell me how can I use that in my above query?
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(new PageRequest(0,1));
Both should yield the same result, without needing to resort to plain SQL.
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
Hardcore the pagination(new PageRequest(0, 1)
) to achieve fetch only one record.
@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value = "true") })
@Query("select * from a_table order by a_table_column desc")
List<String> getStringValue(Pageable pageable);
you have to pass new PageRequest(0, 1)
to fetch records and from the list fetch the first record.
You can use something like this:
@Repository
public interface ICustomerMasterRepository extends CrudRepository<CustomerMaster, String>
{
@Query(value = "SELECT max(c.customer_id) FROM CustomerMaster c ")
public String getMaxId();
}
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();
来源:https://stackoverflow.com/questions/44565820/what-is-the-limit-clause-alternative-in-jpql