openSessionInView的使用原理及性能分析

        看到好多项目中用到了openSessionInView,这种做法无非是开发方便,能够在JSP页面中操作数据库层方面的业务。

下边说下openSessionInView的使用方法及性能问题。

        使用:

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

SessionFactory sessionFactory = lookupSessionFactory(request);
Session session = null;
boolean participate = false;

if (isSingleSession()) {
	// single session mode
	if (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 mode
	if (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 mode
		TransactionSynchronizationManager.unbindResource(sessionFactory);
		logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
		closeSession(session, sessionFactory);
	}else {
		// deferred close mode
		SessionFactoryUtils.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的简单原理图,有点简陋,不喜勿喷:


原文地址:https://www.cnblogs.com/yfceshi/p/7048411.html