设为首页 加入收藏

TOP

openSessionInView的使用原理及性能分析
2015-07-20 17:54:43 来源: 作者: 【 】 浏览:2
Tags: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的配置信息

  
	
   
    OpenSessionInView
   
	
   
    com....OpenSessionInView
   

  

  
	
   
    OpenSessionInView
   
	
   
    /*
   

  
3、在具体的Jsp页面中取SESSION操作数据



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

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

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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ 3282 Ferry Loading IV(模拟,.. 下一篇hdu 1087 简单dp

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: