Not sure if your “editing” means you found all the answers. NHibernate breaks the caching mechanism into two areas.
The first is a cache class, as described above. Any request for an object with a specific identifier (Session.Get (id) ;, reference property, collection) can be used by the class cache.
The second is the query cache. In this case, the key used for cache depends on the Criteria passed. They were used to get a set of results (where, order, top ...). In this case, cache is the set of identifiers returned by this request.
So, when the same criteria are applied, the cached set of identifiers is returned, and the cached objects from the class cache (by identifier) are reused.
(The specific scenario is applicable to projection, which can also be cached in recent versions of NHibernate. In this case, the results do not contain an object with a unique identifier, but a set of columns. Although they are not suitable for identifier-based caching, it works as well. Version 3.3 does this for me)
So, to finally answer:
But when I get an object using criteria, there are always SQL queries ...
we must also enable the query cache:
<property name="cache.use_second_level_cache">true</property> <property name="cache.use_query_cache">true</property>
A second level cache is allowed, and objects with an identifier can be saved. Support for the query cache is also supported, so the second call to the same combination of criteria should not go to the SQL server at all.
Caching an example request:
criteria.SetCacheable(true) .SetCacheMode(CacheMode.Normal) .SetCacheRegion("LongTerm");