【问题标题】:Only last record from Custom query仅来自自定义查询的最后一条记录
【发布时间】:2019-01-31 18:05:47
【问题描述】:

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

@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 查询以实现我的想法?

【问题讨论】:

  • 当查询本身没有定义排序时,“last”的含义有点模糊。没有它,您无法保证排序是一致的。
  • JPA find the Last entry的可能重复
  • 如果我有列表记录,我想获得具有最大 id 值的记录

标签: java sql spring spring-data-jpa


【解决方案1】:

一种可能的解决方案是使用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中没有办法使用limit,所以可以使用Pageable

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

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

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

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

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

【讨论】:

    【解决方案2】:

    您需要为查询提供更多参数,尤其是ORDER BY 子句。

    要获取最新的seanceId,您需要按该 ID 对结果进行排序,但顺序相反。然后,告诉查询只返回第一个结果:

    SELECT r FROM Reservation r 
    WHERE r.reservationSeance.id=:seanceId 
    AND r.seanceDate=:seanceDate 
    ORDER BY seanceId 
    DESC LIMIT 1;
    

    【讨论】:

      【解决方案3】:

      如果您使用mysql 作为数据库,您可以尝试以下操作:

      SELECT r 
      FROM Reservation r 
      WHERE r.reservationSeance.id=:seanceId 
        AND r.seanceDate=:seanceDate 
      order by r.reservationSeance.id desc limit 0,1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-25
        相关资源
        最近更新 更多