I was going through hibernate and situations when to use Criteria vs HQL
and my understanding is that with Hibernate, everytime when we are querying database either by Criteria
or HQL
in both instances hibernate would get result set and put in memory and then when we call that query again, data would be fetched from memory rather then hitting that database, is my understanding correct?
Also as you can see from comments to question mentioned below, it was suggested that Hibernate Criteria would get data from session and HQL would always go and hit database and so any number of multiple calls to HQL query will go and hit database and if this is the case then HQL
causes more problems than solving.
Kindly advise on this as am little bit confused with the situation.
Reference to question
Basically if you're generating queries you're probably going to hit the database, the exception to this is if you've cached the query and parameters.
Hibernate queries (whether you use Criteria or HQL) will only return entities from the session cache (first level cache) if you get it with the @Id.
In order to cache a query you can use the following syntax:
Edited for comments:
A query is not the same as a get with @Id. To get an object by its @Id you would write something like:
It depends on what kind of queries you are making and about your cache settings.
Hibernate has three kind of caches: session cache, query cache and 2nd level cache. Session cache is always on but the other two can be disabled.
Usually the caching is not the reason to favor Criteria API over HQL or vice versa. They are mostly just different interfaces for essentially the same thing.
See http://www.javalobby.org/java/forums/t48846.html and http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html