In NHibernate
you can easily benefit from first level cache when using Load
or Get
methods. But what about ICriteria
, HQL
, Linq-to-NHibernate
and QueryOver
? Do they use first level cache too?
Asked
Active
Viewed 740 times
4

Afshar Mohebi
- 10,479
- 17
- 82
- 126
2 Answers
5
They use it for returning entities, but the queries go straight to the db unless you use the second level cache.
Consider this:
var fooUsingGet = session.Get<Foo>(fooId);
var fooQueryById = session.Query<Foo>().Single(f => f.Id == fooId);
Two queries are executed (one for the Get, one for the Query), but both variables contain the same object reference.
Now, if you enable the 2nd level cache, query caching, and specify caching for the query:
var fooQueryById = session.Query<Foo>().Cacheable()
.Single(f => f.Id == fooId);
var fooQueryByIdAgain = session.Query<Foo>().Cacheable()
.Single(f => f.Id == fooId);
Only one query will be executed.

Diego Mijelshon
- 52,548
- 16
- 116
- 154
-
1Just a note for future people: In your first block of code, (get followed by query) two queries are indeed executed. However, change the order (query followed by get) and you only see ONE - because first level cache kicks in - the query primes the cache. This is contrary to ayendes "Get, Load, query by Id" article - but that seems to reference an earlier version of the linq driver – Peter McEvoy Oct 13 '15 at 11:26
0
No, as I understand they don't. They use only second level cache. Firs level cache is only for Get
and Load
.

gor
- 11,498
- 5
- 36
- 42