开发者

Questions about nhibernate

I have a couple questions about nhibernate.

  1. I still don't understand what contextual sessions means. I do web stuff so I just choose "web" but I really don't know what it is doing.

  2. Should I put session.BeginTransaction() in Application_BeginRequest?

  3. Should I commit everything in Application_EndRequest? Or should I commit when needed. Say I need to insert a user and the开发者_C百科n down in some code later I need to update some other table. Should I make the user and do the update then finally commit or should I wait till both are ready to be commited?

  4. Should you always have session.Rollback() in Application_EndRequest?

  5. Should I session.close() or session.dispose() or both in Application_EndRequest?


  1. "web" context means there can only be a single "current" Session per SessionFactory per HttpContext (i.e. per request). It's your responsibility to bind/unbind it.

  2. Without going too deep, I'd say that's fine, as long as you want to equate 1 request == 1 transaction.

  3. Remember the session is a unit of work. Although you could have multiple transactions in a single request, it's not very common, so I'd say you should commit on EndRequest, unless there was an error (keeping it consistent with your 2nd question)

  4. Not necessarily. You can call it if there's an error, although disposing it would have the same effect.

  5. Dispose is enough.


For information on contextual sessions, check out this link.

As for your other questions, they're all sort of related. Hibernate transactions should be atomic, but moreover, the scope of a transaction and its session should be limited to a unit of work. In other words, you should open a session when you need to persist or retrieve something and close it when you are done.

Generally, it's good practice to use a DAO design pattern for Hibernate in conjunction with some sort of session manager that will give you a singleton session.

I would highly recommend reading this article on Hibernate sessions and transactions. It explains what I just talked about in more depth and discusses how to implement a DAO pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜