我试图通过使用限制查询来限制查询结果。超出限制时,查询按预期工作。
@Query("SELECT a FROM DrmAdpodTimeSlot a where a.startTime > :startTime order by a.startTime desc")
public List<DrmAdpodTimeSlot> findByStartTime(@Param("startTime") Timestamp startTime);
但是当我尝试使用limit(no.of记录)限制记录时,如下所示,
@Query("SELECT a FROM DrmAdpodTimeSlot a where a.startTime > :startTime order by a.startTime desc limit 2")
public List<DrmAdpodTimeSlot> findByStartTime(@Param("startTime") Timestamp startTime);
从上面的查询中我收到以下错误,
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: limit near line 1, column 110 [SELECT a FROM com.dooreme.domain.DrmAd
podTimeSlot a where a.startTime > :startTime order by a.startTime desc limit 2]
如何在spring data jpa query中使用限制查询命令?
答案 0 :(得分:4)
您无法为Query
注释添加分页支持。当您使用Spring Data JPA时,无需在HQL/JPQL
中添加排序和分页功能。请改用Pageable
作为第二个参数,如下所示:
@Query("SELECT a FROM DrmAdpodTimeSlot a where a.startTime > :startTime")
public List<DrmAdpodTimeSlot> findByStartTime(@Param("startTime") Timestamp startTime, Pageable pageable);
Pageable
包围排序和分页功能,正如spring data jpa doc所说:
将
Pageable
实例添加到查询方法以动态添加分页 您的静态定义查询。Page
知道总数。{1}} 元素和页面可用。它是由基础设施实现的 触发计数查询以计算总数。就这样 可能很昂贵,具体取决于所使用的商店,Slice
可以用作 返回。Slice
只知道是否存在下一个Slice
步行时想的更大可能就足够了 结果集。
所以,你可以使用:
@Query("SELECT a FROM DrmAdpodTimeSlot a where a.startTime > :startTime")
public Page<DrmAdpodTimeSlot> findByStartTime(@Param("startTime") Timestamp startTime, Pageable pageable);
或者:
@Query("SELECT a FROM DrmAdpodTimeSlot a where a.startTime > :startTime")
public Slice<DrmAdpodTimeSlot> findByStartTime(@Param("startTime") Timestamp startTime, Pageable pageable);
此外:
排序选项也通过Pageable实例处理。
答案 1 :(得分:0)
其他答案都没有真正回答您如何限制前 2 个开始时间降序的问题。我不确定如何使用 jpql,但使用 jpa 查询,您可以执行 findTop2ByOrderByStartTimeDesc
另外,请看这篇文章 How would I write SELECT TOP 25 sql query in Spring data repository 您可以在存储库中使用您的查询:
@Query("SELECT a FROM DrmAdpodTimeSlot a WHERE a.startTime>'?1' ORDER BY a.startTime DESC")
List<DrmAdpodTimeSlot> findByStartTime(String startTime, Pageable pageable);
}
在服务中,使用一个 PageRequest,返回一个 Page 对象:
Page<DrmAdpodTimeSlot> top2 = arcustRepository.findByStartTime(arcustno, PageRequest.of(0, 2));
List<DrmAdpodTimeSlot> top2StartTimes = top2.getContent();