Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to fetch only 5 records with HQL [duplicate]

Possible Duplicate:
How do you do a limit query in HQL

I am new to HQL. I have following working HQL query:

from Order as o where o.account.profile.userId='abc' order by o.orderID desc

This query returns me list of orders placed by user abc . User can have 0 to 5000+ orders placed in DB. But I want to display only First 5 records(Orders). I am using sublist function of java List.

Can I directly fetch only first 5 records using HQL query? which is more efficient way to write this query?

like image 690
Sagar Avatar asked May 18 '11 08:05

Sagar


People also ask

Can we use distinct in HQL query?

Using distinct in the HQL Query We can notice that the distinct keyword was not only used by Hibernate but also included in the SQL query. We should avoid this because it's unnecessary and will cause performance issues.

What is the difference between JPQL and HQL?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.

Is HQL faster than SQL?

You can select only certain columns with HQL, too, for example you can use select column from table in HQL. Native SQL is not necessarily faster than HQL. HQL finally also is translated into SQL (you can see the generated statement when running the application with the show_sql property set to true).


2 Answers

You can limit the results returned by a query by calling the setFirstResult() and setMaxResults() functions on the query object before running the query. Like so:

Query query = session.createQuery("from Order as o where o.account.profile.userId='abc' order by o.orderID desc");
query.setFirstResult(0);
query.setMaxResults(5); 
List result = query.list();

It depends on your DBMS used whether this will be handled in the DBMS directly.

like image 142
Florian Avatar answered Sep 21 '22 18:09

Florian


Use Criteria.setMaxResults(..):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html

like image 35
abalogh Avatar answered Sep 17 '22 18:09

abalogh