Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate cache expiration

I use custom developed ORM currently and am planing to move to nhibernate.

Currently, I use both L1 - session level caching and L2 - Application level caching.

Whenever an object is requested from L2 cache by L1 cache, it checks database for modified since last load, and loads only if it has been modified.

Can I do this with NHibernate. In short, caching does not hurt me as it always gets most recent data and saves me object creation and load times.

like image 321
Rohit Avatar asked Jun 13 '09 16:06

Rohit


People also ask

How does NHibernate cache work?

An NHibernate session has an internal (first-level) cache where it keeps its entities. There is no sharing between these caches - a first-level cache belongs to a given session and is destroyed with it. NHibernate provides a second-level cache system; it works at the session factory level.

How do I clear NHibernate cache?

NHibernate will evict associated entities automatically if the association is mapped with cascade="all" or cascade="all-delete-orphan". The ISession also provides a Contains() method to determine if an instance belongs to the session cache. To completely evict all objects from the session cache, call ISession. Clear().


1 Answers

IMHO it's pointless to have an L2 cache if it needs to hit the DB anyway. That's precisely the entire point of caching, avoid hitting the DB as much as possible.

AFAIK there is no caching strategy implemented like the one you describe, but NHibernate L2 caches are entirely pluggable so you could implement it. However, I wouldn't, for the reasons I mentioned above.

Getting outdated data is only an issue if there are other apps or other DALs hitting the same DB besides NHibernate. If that's the case, you could use the SysCache2 implementation, which internally uses SqlCacheDependencies to invalidate cache regions when data in the underlying table changes.

If it's a single app running in a farm, use the Velocity provider.

If there's only one NHibernate app instance hitting the DB, any cache strategy will do and you don't have to worry about getting outdated data.

See also:

  • NHibernate docs about 2nd-level caching
  • NHibernate 2nd Level Cache @ NHibernate Forge
  • First and Second Level caching in NHibernate @ The NHibernate FAQ
  • Ayende's posts about NHibernate caching
like image 110
Mauricio Scheffer Avatar answered Sep 18 '22 18:09

Mauricio Scheffer