'Are query results cached by Java/Hibernate?
Our codebase has a lot of examples of the following code:
singleResult = q.list().isEmpty() ? null : q.list().get(0);
and I'm currently in the process of replacing it with
List l = q.list();
singleResult = l.isEmpty() ? null : l.get(0);
I'm assuming that Hibernate executes the query when list()
is called, but is the result cached in the query object or will it hit the database twice?
Alternatively, does the Java compiler break out the two calls similar to what I'm doing (by default or if I increase optimization level)?
Solution 1:[1]
Hibernate executes the query when query.list()
is called every time, unless you set query.setCacheable(true)
Query query = sessionFactory.getCurrentSession().createQuery("SELECT * FROM USER");
query.setCacheable(true);
return query.list().isEmpty() ? null : query.list().get(0);
Reference: https://www.tabnine.com/code/java/methods/org.hibernate.Query/list
Solution 2:[2]
If I understand your question properly, you are asking if database call happens twice if you use
List l = q.list();
singleResult = l.isEmpty() ? null : l.get(0);
i.e. calling q.list()
first & then again using l.isEmpty()
.
Answer to this question is No, because you have already called q.list()
& returned result to reference l
.
call l.isEmpty()
will get applied to result which you have returned in first line.
Regarding hiberanate caching, unless you set query.setCacheable(true)
, your every call to q.list()
will hit db.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pramod H G |
Solution 2 | Ashish Patil |