Question

I query my NHibernate datasources using a Linq Expression. The problem I have with that is that no two invocations (or evaluations, sorry for the bad vocabulary) of the expression ever match in a comparison. As a consequence, NHibernate executes the same SQL with the same parameters way too often.

I shipped around this issue by using NHibernate Caches, fluently configured like so:

Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
                    .ConnectionString(c => c.Is(cStr))
                    .ShowSql())
                    .Mappings(x => x.FluentMappings.AddFromAssemblyOf<MyClassMap>())
                    .Cache(x=>x.UseQueryCache()
                               .ProviderClass("NHibernate.Cache.HashtableCacheProvider"))

I will take care of the provider later, so that this won't end up in production. Next, all my queries are denoted as being cacheable:

session.Query<MyClass>().Cacheable().Where(filter).ToList();

As far as I have read, caching queries happens in the second level cache, which has a one-per-SessionFactory scope. That, on the other hand, means that in order to reload my application data, I would have to reinstatiate the SessionFactory, which I think is much more costly than doing the same thing with sessions.

Is an efficient way to cache the queries without messing (not literally, y'know what I mean) with the SessionFactory?

Was it helpful?

Solution

You can clear second level-cache (http://stackoverflow.com/questions/2660714/how-to-clear-the-entire-second-level-cache-in-nhibernate) without recreating SessionFactory but i am not sure that provided code clears cached queries too. And also there are methods to clear specific providers with their api. But as i know you have to manually clear cache only if you change data in db manually (not with NHibernate). If you change something with NH it will update cache itself. But if you change queried data very often than cache won't help you because it will have to be updated too often.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top