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. Beca开发者_StackOverflow社区use 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?
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.
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.
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.
精彩评论