Currently, in our ASP.NET application, we have 1 session per request and each time we download or update the object we create one transaction. See below:
public static T FindById<T>(object id) { ISession session = NHibernateHelper.GetCurrentSession(); ITransaction tx = session.BeginTransaction(); try { obj = session.Get<T>(id); tx.Commit(); } catch { session.Close(); throw; } finally { tx.Dispose(); } return obj; } public virtual void Save() { ISession session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); try { if (!IsPersisted) { session.Save(this); } else { session.SaveOrUpdateCopy(this); } transaction.Commit(); } catch (HibernateException) { if (transaction != null) { transaction.Rollback(); } if (session.IsOpen) { session.Close(); } throw; } finally { transaction.Dispose(); } }
Obviously, this is not ideal, as it means that you create a new database connection every time you load or save an object, which is associated with performance overhead.
Questions:
- If the object is already loaded into the 1st level cache will the Call GetTransaction () open the database connection? I suspect it will be ...
- Is there a better way to deal with our transaction transaction management less and therefore less database connections?
Unfortunately, the application code is probably too mature to structure everything like this (using get and update all in one transaction):
using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var post = session.Get<Post>(1);
Would it be a terrible idea to create one transaction per request and pass it at the end of the request? I assume the downside is that it connects one connection to the database, while operations without the database occur.
source share