I've set class-cache in nhibernate.cfg.xml file.
When I get my entity by Id, I don't see SQL requests once object is loaded.
But when I fetch entity using criteria, there is always SQL queries...
EDIT:
I guess this answers my question:
http://www.javalobby.org/java/forums/t48846.html
Let's say that we wanted to lookup entries based on a more complex query than directly by ID, such as by name. In this case, Hibernate must still issue an SQL statement to get the base data-set for the query. So, for instance, this code:
Query query = session.createQuery("from Person as p where p.firstName=?"); query.setString(0, "John"); List l = query.list(); ... would invoke a single select (assuming our associations were cached).
select * from Person where firstName='John' This single select will then return '1', and then the cache will be used for all other lookups as we have everything cached. This mandatory single select is where the query cache comes in.
Not sure if your "edit" means that you've found all answers. NHibernate splits the caching mechanism into two areas.
The First is the "class" cache, as mentioned above. Any request for an object with specific ID (Session.Get(id);, referenced property, collection), the class cache could be used.
The Second is the "query" cache. In that case, the key used for cache depends on passed
Criteria
. Those were used to get the result set (where, order by, top ...). The value cached in this case is a set of IDs, returned by that query.So later, when the same criteria are applied, cached set of IDs is returned and cached entities from a class-cache (by ID) are reused.
(Specific scenario applies to projection, which in the latest NHibernate versions could be cached as well. In that case, the results does not contain entity with unique ID, but a set of columns. While not fitting into ID based caching, it is working as well. Version 3.3 is doing that for me)
So, to finally answer:
we have to allow the query cache as well:
Second level cache is allowed and objects with ID can be stored. Also the support for query cache is enabled, so the second call of the same Criteria combination should not go to SQL server at all.
Caching the query example: