Organizational Research By

Surprising Reserch Topic

how do you do a limit query in hql

how do you do a limit query in hql  using -'java,hibernate,hql'

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 seems to have disappeared.

asked Sep 9, 2015 by HungKahlctcu
0 votes

Related Hot Questions

6 Answers

0 votes

This was posted on the Hibernate forum a few years back when asked about why this worked in Hibernate 2 but not in Hibernate 3:

Limit was never a supported clause in HQL. You are meant to use setMaxResults().

So if it worked in Hibernate 2, it seems that was by coincidence, rather than by design. I think this was because the Hibernate 2 HQL parser would replace the bits of the query that it recognised as HQL, and leave the rest as it was, so you could sneak in some native SQL. Hibernate 3, however, has a proper AST HQL Parser, and it's a lot less forgiving.

I think Query.setMaxResults() really is your only option.

answered Sep 9, 2015 by VictoriaKoy
0 votes
 // SQL: SELECT * FROM table LIMIT start, maxRows;

Query q = session.createQuery("FROM table");
answered Sep 9, 2015 by KarPenn
0 votes

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

answered Sep 9, 2015 by Ila9050
0 votes

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.

answered Sep 9, 2015 by TimmyG26nrd
0 votes

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)

answered Sep 9, 2015 by EulUpton
0 votes

If can manage a limit in this mode

public List listExampleModel() {
    return listExampleModel(null, null);

public List listExampleModel(Integer first, Integer count) {
    Query tmp = getSession().createQuery("from ExampleModel");

    if (first != null)
    if (count != null)

    return (List)tmp.list();

This is a really simple code to handle a limit or a list.

answered Sep 9, 2015 by SalFay