Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using setMaxResults(1) before uniqueResult() for hibernate optimization?

Is writing

session.createCriteria(Person.class) .add(Restrictions.eq("id", personId)) .setMaxResults(1) .uniqueResult();

better than writing

session.createCriteria(Person.class) .add(Restrictions.eq("id", personId)) .uniqueResult();

from an optimization point of view? Will the first query be faster?

like image 279
darksmurf Avatar asked Mar 23 '16 10:03

darksmurf


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 setMaxResults?

Query setMaxResults(int maxResult) Set the maximum number of results to retrieve. Parameters: maxResult - maximum number of results to retrieve Returns: the same query instance Throws: IllegalArgumentException - if the argument is negative.

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

Sometimes explicitly limiting the result set rows to the expected number may give a hint to the database to build a more optimized query execution plan.

However, in most databases querying by primary key is the most optimal filter condition anyway so any additional conditions will bring no benefit. Actually, the additional sql fragment will just increase the statement parsing time and time spent by the db optimizer discarding the redundant filter conditions.

like image 200
Dragan Bozanovic Avatar answered Nov 15 '22 08:11

Dragan Bozanovic