Second Level Cache with NHibernate

93 views
Skip to first unread message

Cameron

unread,
Jul 6, 2011, 6:14:09 AM7/6/11
to nhusers
I’m thinking to use NHibernate with a second level cache. Which one
would be good option?
Is there any second level cache that can be used with NHibernate and
how? Actually I’m totally new and don't have any experience in it I
have just heard the names like NCache, ehcache, AppFabric etc.
Good suggestions would be appreciated
Thanks in advance

Jason Meckley

unread,
Jul 6, 2011, 10:15:56 AM7/6/11
to nhu...@googlegroups.com
the nhcontrib project has a number of cache implementations already. it's a powerful feature, but it's not simplistic. i would caution the use of 2nd level cache until all other options for optimizing data access are exhausted. i.e.
*eliminate select n+1
*batched reads/writes
*query/index optimization

configuring 2nd level cache is an advanced feature of NH and requires quite a bit of configuration. It's also easy to hurt performance, rather than improve if the configurations are not correct.

for nhibernate.cfg.xml
1. enable 2nd level cache
2. define which cache implementation to use
3. configure the cache implementation (each one is different)

then for each entity you want to cache
1. enable cache for the entity
2. define how to cache (read-write, read-only, etc.)
3. also take care in whether related entities and collections are cached.

you can also cache queries and projections, which requires it's own configuration as well.

2nd level cache is tied closely to transactions, this is another reason for wrapping all session calls (both reads and writes) in a transaction. If they are not the cache becomes corrupt.

in closing, by definition cache is stale data. At any given point in time it may be out of sync with the database. It seems a lot of people forget this fact and expect the cache to match the database at all times. This assumption then leads to all kinds of problems and difficult to spot bugs.

2nd level cache is an awesome feature, but I wouldn't use it until you have no other way to improve performance, and performance is a quantified problem.
Reply all
Reply to author
Forward
0 new messages