David
David

Reputation: 16120

How to get NHibernate ISession to cache entity not retrieved by primary key

My 'user' entity is almost always retrieved by username, rather than by its integer surrogate key. Because the username is not the primary key, this means that the ISession won't cache it and repeatedly hits the database to get the same data.

Is there any way at all I can configure NHibernate to get the ISession to cache users retrieved by username?

Upvotes: 1

Views: 1229

Answers (3)

Diego Mijelshon
Diego Mijelshon

Reputation: 52725

The "session cache" is actually not a cache, but an entity map.

My suggestion is that you enable the 2nd level cache for queries using a custom provider that stores items in the HttpContext.

Upvotes: 1

David
David

Reputation: 16120

It seems the answer is in fact no. Yes, if you're using the second level cache, no if you are using the Session cache.

Upvotes: 2

Jamie Ide
Jamie Ide

Reputation: 49251

Yes, you can use NHibernate's natural-id element to accomplish this. See http://ayende.com/Blog/archive/2009/06/23/nhibernate-ltnatural-idgt.aspx, the example is exactly what you're asking for.

Upvotes: 1

Related Questions