Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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.

2 Answers

0 votes
by (46k points)

Try:

 // SQL: SELECT * FROM table LIMIT start, maxRows;

Query q = session.createQuery("FROM table");

q.setFirstResult(start);

q.setMaxResults(maxRows);

0 votes
by (3.1k points)

You will have to use the setMaxResults() method because the LIMIT keyword is not directly supported by HQL itself to set a limit on the results of a query in HQL. 

Example Code 

Query query = session.createQuery("FROM EntityName e WHERE e.property = :value"); 

query.setParameter("value", someValue); 

query.setMaxResults(10); // Limits the result to 10 entries 

List<EntityName> results = query.list(); 

Explanation 

the code has been explained below 

setMaxResults(int maxResults): Sets the maximum number of rows to be retrieved. 

This limits the results without altering the syntax of the HQL query itself. 

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...