How do you do a limit query in HQL?

2018-12-31 17:56发布

In Hibernate 3, is there a way to do the equivalent of the following MySQL limit in HQL?

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

I don't want to use setMaxResults if possible. This definitely was possible in the older version of Hibernate/HQL, but it seems to have disappeared.

9条回答
余生无你
2楼-- · 2018-12-31 18:18
 // SQL: SELECT * FROM table LIMIT start, maxRows;

Query q = session.createQuery("FROM table");
q.setFirstResult(start);
q.setMaxResults(maxRows);
查看更多
泪湿衣
3楼-- · 2018-12-31 18:26

String hql = "select userName from AccountInfo order by points desc 5";

This worked for me without using setmaxResults();

Just provide the max value in the last (in this case 5) without using the keyword limit. :P

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 18:27

My observation is that even you have limit in the HQL (hibernate 3.x), it will be either causing parsing error or just ignored. (if you have order by + desc/asc before limit, it will be ignored, if you don't have desc/asc before limit, it will cause parsing error)

查看更多
闭嘴吧你
5楼-- · 2018-12-31 18:28

If you don't want to use setMaxResults() on the Query object then you could always revert back to using normal SQL.

查看更多
若你有天会懂
6楼-- · 2018-12-31 18:28

If you don't want to use setMaxResults, you can also use Query.scroll instead of list, and fetch the rows you desire. Useful for paging for instance.

查看更多
高级女魔头
7楼-- · 2018-12-31 18:35

You need to write a native query, refer this.

@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);
查看更多
登录 后发表回答