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.
1 Answer. Try: // SQL: SELECT * FROM table LIMIT start, maxRows; Query q = session.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With