I have a jpql as:
@Query("SELECT b FROM Booking b WHERE "
+ "(:officeId is null OR b.officeId = :officeId) AND "
+ "(:status is null OR b.status = :status) AND "
+ "(:type is null OR b.officeType = :type) "
+ "ORDER BY CASE WHEN b.guestId in (SELECT userId FROM MeetingRoomQuotaRequest) THEN 0 ELSE 1 END")
Page<Booking> findAndOrderByQuotaRequestExists(
@Param("officeId") String officeId,
@Param("status") Status status,
@Param("type") OfficeType type,
Pageable pageable);
In this JPQL I am searching the query according to officeId, status, type optional fields so if they are null then I just ignore them. It is working good if I don’t send the sort function. But if I send sort parameter then it is getting error:
Pageable sort function is added to the end of the sql and it is getting syntax error:
[SELECT b FROM Booking b WHERE (:officeId is null OR b.officeId = :officeId) AND (:status is null OR b.status = :status) AND (:type is null OR b.officeType = :type) ORDER BY CASE WHEN b.guestId in (SELECT userId FROM MeetingRoomQuotaRequest) THEN 0 ELSE 1 END order by b.createdOn desc];
As you see at the end it is adding order by b.createdOn desc
but it must be separated just with comma(,) instead of putting 'order by'
again.
How can I modify the jpql to get page with optional params and also pageable sort options ?
2
Answers
JPQL generates queries from static rules it has been defined on. It cannot know that you have already defined one order by explicitly. So you can get around this by putting
b.guestId in (SELECT userId FROM MeetingRoomQuotaRequest)
clause inwhere
clause of first statement.Ya you noticed yoi can add the raw
ORDER BY
to the query directly, you need to assSort object instance
and add it to thefindAndOrderByQuotaRequestExists