We are using Hibernate in our project. My question is regarding named queries. Can someone guide me on how named queries are handled by Hibernate. If Hibernate is configured to use level 1 cache will it also return results for the named query from the cache or will it always make a trip to the database?
Asked
Active
Viewed 2,592 times
1 Answers
3
The level-1 cache is the Hibernate session. Except in very rare case where a stateless session is used, there is a level-1 cache by default. Queries results are never cached in the level-1 cache. I think you meant "second-level cache".
Named queries are handled exactly like unnamed-queries regarding the cache.
Queries can be cached or not. If they're cached, a round-trip to the database can be avoided. Whether they're cached or not, if they return instances of entities that are in the second-level cache, the query will return the IDs, and then the entities themselves will be loaded from the second-level cache.
See Hibernate 2nd level cache in a Grails app and the reference documentation for more information.
-
Thanks Nizet. Sorry, yes I meant second-level cache. I will try to explain a little more. I have an entity and my named query is selecting the entity based on two parameters. So in this case will hibernate select from the cache or the database? – java_buzz Feb 28 '12 at 15:06
-
It never selects from the cache. It goes to the database and, if the query is cachable, it stores its results in the query cache. If you execute the same query, with the same parameters, a second time, the results will be loaded from the query cache. – JB Nizet Feb 28 '12 at 15:24
-
Thanks for your help Nizet. The query_cache should be set to true for caching to be implemented for the queries else it would go to the database every time. – java_buzz Feb 28 '12 at 15:40