Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL - row identifier for pagination

Does anyone know if HQL has a keyword to identify rows such as ROWID or ROWNUM?

I would like to implement pagination with HQL but I am not able to use .setMaxResult() or .setFirstResult() because I don't work with the session object directly and therefore don't use the Query object but simply create my query as a string and use the .find() method.

I tried using LIMIT and OFFSET in my query, but HQL seems to be ignoring these keywords and is returning the whole result to me no matter what.

I'm also not able to use Hibernate criteria because it does not have support for the "HAVING" clause that appears in my query.

My last resort is to restrict the result set using the ROWNUM/ROWID keyword. Does anyone else have any other suggestions?

like image 724
user57701 Avatar asked Jan 28 '09 21:01

user57701


People also ask

What is pagination in HQL?

Pagination is a simple but important feature to limit the size of your result set to a number of records that can get efficiently processed by your application and the user. You can configure it with JPA and Hibernate by calling the setFirstResult and setMaxResults on the Query or TypedQuery interface.

How to do pagination using Hibernate?

The simplest and most common way to do pagination in Hibernate is using HQL: Session session = sessionFactory. openSession(); Query query = sess. createQuery("From Foo"); query.

How does Hibernate HQL work?

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.


1 Answers

this is one situation where hibernate shines:

typical solution with hql query.

int elementsPerBlock = 10;
int page = 2;

return  getSession().createQuery("from SomeItems order by id asc")
            .setFirstResult(elementsPerBlock * (page-1) + 1 )
            .setMaxResults(elementsPerBlock)
            .list();

hibernate will translate this to a pattern that is understood by the database according to its sql dialect. on oracle it will create a subselect with ROWNUM < X. on postgresql it will issue a LIMIT / OFFSET on msSQL server it will issue a TOP..

to my knowledge it is not possible to achieve this with "pure" hql.

like image 172
Andreas Petersson Avatar answered Sep 24 '22 15:09

Andreas Petersson