AwkwardCoder
AwkwardCoder

Reputation: 25631

fluent nhibernate not caching queries in asp.net mvc

I'm using a fluent nhibernate with asp.net mvc and I not seeing anything been cached when making queries against the database. I'm not currently using an L2 cache implementation.

Should I see queries being cached without configuring an out of process L2 cache?

Mapping are like this:

 Table("ApplicationCategories");
 Not.LazyLoad();
 Cache.ReadWrite().IncludeAll();
 Id(x => x.Id);
 Map(x => x.Name).Not.Nullable();
 Map(x => x.Description).Nullable();

Example Criteria:

 return session
          .CreateCriteria<ApplicationCategory>()
          .Add(Restrictions.Eq("Name", _name))
          .SetCacheable(true);

Everytime I make a request for an application cateogry by name it is hitting the database is this expected behaviour?

Upvotes: 1

Views: 1062

Answers (2)

Diego Mijelshon
Diego Mijelshon

Reputation: 52745

You need to enable the second level cache and the query cache in order to cache queries.

This has nothing* to do with "level 1" caching (session identity map).

If you add the following properties to your NHibernate config file:

<property name="cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</property>
<property name="cache.use_query_cache">true</property>

...The DB will not be hit in subsequent calls.

Upvotes: 1

James Gregory
James Gregory

Reputation: 14223

Level 1 caching is only at the session level, once you dispose that session your cache goes with it. I assume, like most web apps, you'll be doing session-per-request; in which case, it's perfectly normal for it to hit the database every time.

The level 1 cache is most useful for when you're going to execute the same (or similar) queries in the same session, and in that case you'll only see the one call to the database.

Upvotes: 3

Related Questions