仅来自自定义查询的最后一条记录 [英] Only last record from Custom query

查看:29
本文介绍了仅来自自定义查询的最后一条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于仅来自自定义查询的最后一条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆