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

吃可爱长大的小学妹 提交于 2019-12-10 22:18:15

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5192529/how-to-get-nhibernate-isession-to-cache-entity-not-retrieved-by-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!