Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does setMaxResults(N) in Hibernate work?

I am using MS SQL server 2008 with Hibernate. the question I have is how Hibernate implements setMaxResults

Take the following simple scenario.

If I have a query that returns 100 rows and if I pass 1 to setMaxResults, will this affect the returned result from the SQL server itself(as if running a select top 1 statement) or does Hibernate get all the results first (all 100 rows in this case) and pick the top one itself?

Reason I am asking is that it would have a huge performance issue when the number of rows starts to grow.

Thank you.

like image 645
user624558 Avatar asked Feb 28 '13 01:02

user624558


People also ask

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.

What is org hibernate fetchSize?

org. hibernate. fetchSize (Long – number of records) Hibernate provides the value of this hint to the JDBC driver to define the number of rows the driver shall receive in one batch. This can improve the communication between the JDBC driver and the database, if it's supported by the driver.


1 Answers

Hibernate will generate a limit-type query, for all dialects which supports limit query. As the SQLServerDialect supports this (see org.hibernate.dialect.SQLServerDialect.supportsLimit(), and .getLimitString()), you will get a select top 1-query.

If you would like to be absolutly sure, you may turn on debug-logging, or enable the showSql-option and test.

like image 66
Aleksander Blomskøld Avatar answered Sep 22 '22 08:09

Aleksander Blomskøld