The Secret Life of NHibernate's Caches
The fastest way to get data from the database is not getting it from the database.
I talked about NHibernate's caches in the past, but I was mostly focused on entities and collection caching. Those are fairly easy to grasp. You load an entity once, and the second time, it doesn't get loaded.
Collections are slightly more complicated, since they require you to know what is going on (otherwise, you may get into a bit of problem, like I did), but they really reduce the amount of work the database has to do, since even the links between the objects are cached.
The problem is that very few applications can be structured so you can always ask for an object by its primary key. This brings us to the next (and probably final) cache.
Let us check an example:
session.CreateQuery(typeof(Post))
.Add(Expression.Like("Content", "User",MatchMode.Anywhere))
.List();
This is a fairly expensive query, and it can't make use of the already existing cache. Even though the data may be on the cache already, NHibernate is not going to use the caches for querying, that is what databases are good at, after all. The query about will hit the database each and every time.
What can we do about it? Well, there is always the...
Query Cache
The query cache can hold the results of both types on NHibernate's queries (Criteria queries, and HQL queries)
(Very partial view of those interfaces)
Let us take the above query and add caching to it:
session.CreateQuery(typeof(Post))
.Add(Expression.Like("Content", "User",MatchMode.Anywhere))
.SetCachable(true)
.List();
Now, NHibernate will cache the results of the query, and next time that you execute the query, you will get it without the expensive hop to the database.
An important note is remembering to add hibernate.cache.use_query_cache = true to the configuration.
Of course, there are quite a bit of issues with caching querying, mostly about the freshness of the data. Which is why you need to make cached queries explictly in the code.
Use with care.
Comments
Comment preview