openSessionInView的使用原理及性能分析

3 篇文章 0 订阅

        看到好多项目中用到了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的简单原理图,有点简陋,不喜勿喷:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值