在Hibernate 3中,是否有一种方法可以在HQL中实现与以下MySQL限制相同的功能?
select * from a_table order by a_table_column desc limit 0, 20;
如果可能的话,我不想使用setMaxResults。在旧版本的Hibernate/HQL中,这是绝对可能的,但它似乎已经消失了。
在Hibernate 3中,是否有一种方法可以在HQL中实现与以下MySQL限制相同的功能?
select * from a_table order by a_table_column desc limit 0, 20;
如果可能的话,我不想使用setMaxResults。在旧版本的Hibernate/HQL中,这是绝对可能的,但它似乎已经消失了。
当前回答
@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);
其他回答
你需要写一个本地查询,参考这个。
@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);
几年前,当被问及为什么这在Hibernate 2中有效而在Hibernate 3中无效时,这篇文章发布在Hibernate论坛上:
限制从来不是一个受支持的条款 在HQL。你是用来使用的 setMaxResults()。
因此,如果它能在Hibernate 2中工作,那似乎是巧合,而不是设计。我认为这是因为Hibernate 2 HQL解析器将替换它识别为HQL的部分查询,并保留其余部分,因此您可以潜入一些本地SQL。然而,Hibernate 3有一个合适的AST HQL解析器,它不那么宽容。
我认为Query.setMaxResults()是你唯一的选择。
下面的代码段用于使用HQL执行限制查询。
Query query = session.createQuery("....");
query.setFirstResult(startPosition);
query.setMaxResults(maxRows);
您可以在此链接获得演示应用程序。
你可以使用下面的查询
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);