在Hibernate 3中,是否有一种方法可以在HQL中实现与以下MySQL限制相同的功能?

select * from a_table order by a_table_column desc limit 0, 20;

如果可能的话,我不想使用setMaxResults。在旧版本的Hibernate/HQL中,这是绝对可能的,但它似乎已经消失了。


当前回答

你可以使用下面的查询

NativeQuery<Object[]> query = session.createNativeQuery("select * from employee limit ?");
query.setparameter(1,1);

其他回答

@Query(nativeQuery = true,
       value = "select from otp u where u.email =:email order by u.dateTime desc limit 1")
public List<otp> findOtp(@Param("email") String email);

下面的代码段用于使用HQL执行限制查询。

Query query = session.createQuery("....");
query.setFirstResult(startPosition);
query.setMaxResults(maxRows);

您可以在此链接获得演示应用程序。

你需要写一个本地查询,参考这个。

@Query(value =
    "SELECT * FROM user_metric UM WHERE UM.user_id = :userId AND UM.metric_id = :metricId LIMIT :limit", nativeQuery = true)
List<UserMetricValue> findTopNByUserIdAndMetricId(
    @Param("userId") String userId, @Param("metricId") Long metricId,
    @Param("limit") int limit);

如果不想使用setMaxResults,也可以使用Query。滚动而不是列表,并获取您想要的行。例如,对于分页很有用。

您可以很容易地为此使用分页。

    @QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value = "true") })
    @Query("select * from a_table order by a_table_column desc")
    List<String> getStringValue(Pageable pageable);

你必须传递new PageRequest(0,1)来获取记录,并从列表中获取第一条记录。