1

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?

David
  • 15,750
  • 22
  • 90
  • 150

3 Answers3

2

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.

David
  • 15,750
  • 22
  • 90
  • 150
  • The answer to the question is no, but the problem can be solved using Sergi Papaseit's answer to this question: http://stackoverflow.com/questions/5272094/architecture-problem-use-of-dependency-injection-resulting-in-rubbish-api – David Mar 11 '11 at 15:24
1

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.

Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
  • 1
    In fact, the natural-id element by itself is not enough; you'll have to enable 2nd level caching. – Frederik Gheysels Mar 04 '11 at 12:49
  • This is what I feared. I don't want to use the second level cache. I use Session-Per-Request, and I don't want cached items to last any longer than that. I think the answer to my question is no. – David Mar 04 '11 at 14:01
1

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.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • In what sense is it not a cache? It stores entities loaded from the database and removes the need for them to be loaded from the database subsequently. That's a cache where I'm from! Thank you for your suggestion about an HttpContext-based cache provider. – David Mar 07 '11 at 09:25