Welcome

首页 / 网页编程 / JSP / openSessionInView的使用原理及性能分析

openSessionInView的使用原理及性能分析2015-07-06看到好多项目中用到了openSessionInView,这样的做法无非是开发方便,可以在JSP页面中操作数据库层方面的业务。下边说下openSessionInView的用法及性能问题。

使用:

1、增加一个Filter,该Filter用来控制事务及数据库的连接管理,代码如下:

SessionFactory sessionFactory = lookupSessionFactory(request);Session session = null;boolean participate = false;if (isSingleSession()) {// single session modeif (TransactionSynchronizationManager.hasResource(sessionFactory)) {// Do not modify the Session: just set the participate flag.participate = true; }else {logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");session = getSession(sessionFactory);TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));}} else {// deferred close modeif (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {// Do not modify deferred close: just set the participate flag.participate = true;} else {SessionFactoryUtils.initDeferredClose(sessionFactory);}}try {filterChain.doFilter(request, response);} finally {if (!participate) {if (isSingleSession()) {// single session modeTransactionSynchronizationManager.unbindResource(sessionFactory);logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");closeSession(session, sessionFactory);}else {// deferred close modeSessionFactoryUtils.processDeferredClose(sessionFactory);}}}

当前代码中只是个例子,具体需要参考自己项目中的实际情况(spring配置,hibernate配置等)
2、在web.xml中增加该Filter的配置信息

<filter><filter-name>OpenSessionInView</filter-name><filter-class>com....OpenSessionInView</filter-class></filter><filter-mapping><filter-name>OpenSessionInView</filter-name><url-pattern>/*</url-pattern></filter-mapping>
3、在具体的Jsp页面中取SESSION操作数据

用法到这里就结束了,下边我们来简单讨论下性能方面的问题

其实大家根据上边的配置就可以想到:对于配置了Filter的处理,每次都会拦截到一个请求,在后台处理之前就会开启一个事物并打开一个数据库连接(线程安全的),后台处理完成后会关闭当前的连接。拦截到所有的请求都这么做,大家觉得opensessioninview的方式性能会好到哪去呢?(如果是匹配某些请求,效果会好那么一点)

画了张opensessioninview的简单原理图,有点简陋,不喜勿喷:

作者:csdn博客 枫飘瞬间