仅来自自定义查询的最后一条记录

问题描述:

以下查询返回一个列表,但我只对列表的最后一个元素感兴趣.

The following query return a list but I am only interested in the last element of the list.

@Query("SELECT r FROM Reservation r WHERE r.reservationSeance.id=:seanceId AND r.seanceDate=:seanceDate")
public Reservation findReservationBySeanceDateAndSeanceId(@Param("seanceId") int seanceId, @Param("seanceDate") java.time.LocalDate seanceDate);

我应该如何重写 SQL-Query 以实现我的想法?

How shall I rewrite the SQL-Query in order to implement my idea?

一种可能的解决方案是使用 ORDER BY r.id DESC :

One possible solution is to use ORDER BY r.id DESC :

@Query("SELECT r FROM Reservation r  " +
        "WHERE r.reservationSeance.id=:seanceId AND r.seanceDate=:seanceDate " +
        "ORDER BY r.id DESC")
public Reservation findReservationBySeanceDateAndSeanceId(
        @Param("seanceId") int seanceId,
        @Param("seanceDate") java.time.LocalDate seanceDate, Pageable pageable);

并且因为在 JPQL 中没有办法使用限制,你可以使用 Pageable

and because there are no way to use limit in JPQL, you can use Pageable

Pageable pageable = new PageRequest(0, 1);
Reservation reservation = r.findReservationBySeanceDateAndSeanceId(seanceId, seanceDate, pageable);

另一种没有查询的可能解决方案:


Another possible solution without Query :

public Reservation findTop1ByReservationSeanceAndSeanceDateOrderByIdDesc(
               ReservationSeanceEntity reservationSenace, 
               java.time.LocalDate seanceDate
)

在第二个解决方案中,您必须传递 ReservationSeance 对象而不是 ReservationSeanceid,查询可以读作:

In this second solution you have to pass the ReservationSeance Object and not the id of ReservationSeance, the query can be read as :

Find top 1 (first one) by `ReservationSeance` and `SeanceDate` order by `Id` Desc order