Questions about nhibernate
I have a couple questions about nhibernate.
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.
Should I put session.BeginTransaction() in Application_BeginRequest?
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?
Should you always have session.Rollback() in Application_EndRequest?
Should I session.close() or session.dispose() or both in Application_EndRequest?
"web" context means there can only be a single "current"
Session
perSessionFactory
perHttpContext
(i.e. per request). It's your responsibility to bind/unbind it.Without going too deep, I'd say that's fine, as long as you want to equate 1 request == 1 transaction.
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)
Not necessarily. You can call it if there's an error, although disposing it would have the same effect.
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.
精彩评论