Refactoring toward frictionless & odorless code: What about transactions?
Join the DZone community and get the full member experience.
Join For FreeOne thing that we haven’t done so far is manage transactions. I am strongly against having automatic transactions that wrap the entire request. However, I do like automatic transactions that wrap a single action. We can implement this as:
public class NHibernateActionFilter : ActionFilterAttribute { private static readonly ISessionFactory sessionFactory = BuildSessionFactory(); private static ISessionFactory BuildSessionFactory() { return new Configuration() .Configure() .BuildSessionFactory(); } public override void OnActionExecuting(ActionExecutingContext filterContext) { var sessionController = filterContext.Controller as SessionController; if (sessionController == null) return; sessionController.Session = sessionFactory.OpenSession(); sessionController.Session.BeginTransaction(); } public override void OnActionExecuted(ActionExecutedContext filterContext) { var sessionController = filterContext.Controller as SessionController; if (sessionController == null) return; using (var session = sessionController.Session) { if (session == null) return; if (!session.Transaction.IsActive) return; if (filterContext.Exception != null) session.Transaction.Rollback(); else session.Transaction.Commit(); } } }
This one is pretty simple, except that you should note that we are
checking if the transaction is active before trying something. That is
important because we might have got here because of an error in the
opening the transaction, we would get a second error which would mask
the first.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
From On-Prem to SaaS
-
Performance Comparison — Thread Pool vs. Virtual Threads (Project Loom) In Spring Boot Applications
-
Adding Mermaid Diagrams to Markdown Documents
-
Operator Overloading in Java
Comments