views:

217

answers:

1

I have a few classes which have a property which is unique to that object, for example for the User class the property Username should never be duplicated.

NHibernate doesn't seem to support loading of an object by unique key which is then cached in the same way that Load() or Get() does. Am I correct when I say that?

If I am then I will just have to role my own via possibly an extension method along the lines of LoadByUniqueIndex(lambda property, object key).

+1  A: 

Yes, you are right, NH doesn't get entities directly from the cache for anything except the id. Note that everything except the id could potentially change and needs to be looked up in the database.

Be careful when caching. "Premature caching is the root of all evil" or whatever. Seriously, if you are not sure that you get notable performance problems, don't write your own cache.

  • Write code that passes entities as arguments to avoid that the same entity is loaded several times.
  • Avoid caches that live longer than a session. You will have stale data if you don't notify all the changes.
  • avoid caches that are static, use thread static instead. This avoids sharing data between sessions, which would break the transaction isolation.
  • Use second level caches if you really need it.

If you consider to have a static cache that lives as long as the application runs, I can tell you that you better avoid it at all. It will not properly work with a reasonable amount of effort.

Stefan Steinegger
Ok thanks Stefan, I'll hold off for now then. At least I know for sure how the caching does work now.
John_