Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate limit result inquiry

Tags:

java

hibernate

How does maxresult property of hibernate query works? in the example below :

Query query = session.createQuery("from MyTable");
query.setMaxResults(10);

Does this get all rows from database, but only 10 of them are displayed? or this is same as limit in sql.

like image 787
Gandalf StormCrow Avatar asked May 06 '11 21:05

Gandalf StormCrow


People also ask

How do I give a limit in HQL?

1 Answer. Try: // SQL: SELECT * FROM table LIMIT start, maxRows; Query q = session.

How do you specify the number of rows to be fetched in select query in hibernate?

Use setMaxResults(int maxResults) to set the maximum number of rows to retrieve. Use the list() API method of Query to get the results. Use again getTransaction() API method of Session and commit() API method of Transaction to commit the Transaction.

Can we use limit in JPA query?

Conclusion. Limiting query results in JPA is slightly different to SQL; we don't include the limit keyword directly into our JPQL. Instead, we just make a single method call to Query#maxResults, or include the keyword first or top in our Spring Data JPA method name. As always, the code is available over on GitHub.

Can you tell the difference between setMaxResults () and setFetchSize () of query?

setMaxResults limits the number of results the query will ever get. setFetchSize tells the jdbc driver how many rows to return in one chunk, for large queries.


1 Answers

It's the same as LIMIT, but it is database-independent. For example MS SQL Server does not have LIMIT, so hibernate takes care of translating this. For MySQL it appends LIMIT 10 to the query.

So, always use query.setMaxResults(..) and query.setFirstResult(..) instead of native sql clauses.

like image 68
Bozho Avatar answered Sep 21 '22 03:09

Bozho