简体   繁体   English

在NHibernate中管理会话的最佳方法是什么?

[英]Best way to manage session in NHibernate?

I'm new to NHibernate (my 1st big project with it). 我是NHibernate的新手(我的第一个大项目)。
I had been using a simple method of data access by creating the ISession object within a using block to do my grab my Object or list of Objects, and in that way the session was destroyed after exiting the code block. 我一直在使用一种简单的数据访问方法,通过在使用块中创建ISession对象来获取我的对象或对象列表,这样会话在退出代码块后就被销毁了。

This doesn't work in a situation where lazy-loading is required, however. 但是,这在需要延迟加载的情况下不起作用。
For example, if I have a Customer object that has a property which is a collection of Orders, then when the lazy-load is attempted, I get a Hibernate exception. 例如,如果我有一个Customer对象,其属性是Orders的集合,那么当尝试延迟加载时,我会得到一个Hibernate异常。
Anyone using a different method? 有人使用不同的方法吗?

查看SummerOfNHibernate网络广播,获得一个很棒的教程......你所寻找的东西直到第5或第6集才会出现。

Keep your session open for your entire unit of work. 为整个工作单元保持会话开放。 If your session is life is too small, you cannot benefit from the session level cache (which is significant). 如果你的会话寿命太小,你就无法从会话级缓存中受益(这很重要)。 Any time you can prevent a roundtrip to the database is going to save a lot of time. 任何时候你都可以防止往返数据库,这将节省大量的时间。 You also cannot take advantage of lazy loading, which is crucial to understand. 您也无法利用延迟加载,这对理解至关重要。

If your session lifetime is too big, you can run into other issues. 如果您的会话生命周期太长,您可能会遇到其他问题。

If this is a web app, you'll probably do fine with the session-per-httpRequest pattern. 如果这是一个Web应用程序,您可能会使用session-per-httpRequest模式。 Basically this is an HttpModule that opens the session at the beginning of the request and flushes/closes at the end. 基本上这是一个HttpModule,它在请求开始时打开会话,并在结束时刷新/关闭。 Be sure to store the session in HttpContext.Items NOT A STATIC VARIABLE. 一定要将会话存储在HttpContext.Items中,而不是静态变量。 <--- leads to all kinds of problems that you don't want to deal with. <---会导致您不想处理的各种问题。

You might also look at RhinoCommons for a unit of work implementation. 您也可以查看RhinoCommons的工作单元实现。

由于您正在开发Web应用程序(可能是使用ASP.NET),请在CodeProject中查看带有ASP.NET的NHibernate最佳实践

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM