`
dylan0514sina.cn
  • 浏览: 92029 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

OpenSessionInViewFilter

 
阅读更多
在一次请求内绑定一个Session到线程,防止Web资源加载时的懒加载问题。HibernateTransactionManager或JTATransactionManager将会使用此Session。非事务运行时(并非事务挂起)也可使用。
该类的flushMode设置为Manual,由于该类一般为事务层提供Session,当Session同步到事务,对于非只读事务(definition指定)由HibernateTransactionManager或SessionFactoryUtils改变flushMode为Auto。如果不在Spring提供事务环境下使用此类,则合理的设置flushMode
singleSession是否在整个请求中使用一个Session,还是每个事务块或操作快使用一个Session,true说明整个请求使用一个Session。对于单个Session来说它从分利用了一级缓存,缺点在于部分的事务失败或访问失败,整个Session必须被废弃;每个事务块或操作快使用一个Session,对事务回滚或方位失败都是可以由应用程序控制重新发起一次事务,同时开相应的Session,当然缺点在于增加了内存消耗。对非单个Session模式来说,延迟加载也是支持的,它使用延迟关闭Session策略。
 具体实现上
 单个Session:Filter或Interceptor负责开Session和绑定SessionHolder到当前线程供整个请求使用,渲染页面之后关闭Session
 每个事务或操作块(HibernateTemplate,HibernateInterceptor)一个Session:Filter或Interceptor负责标识SessionFactory延迟,每个事务或操作块会在代理实现中打开一个Session同时处理具体代理操作之后将新开的Session添加到SessionFactory对应的延迟戴处理的集合中,渲染页面之后关闭该SessionFactory对应的Session集合。

/*
 * Copyright 2002-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.orm.hibernate3.support;

import java.io.IOException;
import java.util.concurrent.Callable;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Servlet 2.3 Filter that binds a Hibernate Session to the thread for the entire
 * processing of the request. Intended for the "Open Session in View" pattern,
 * i.e. to allow for lazy loading in web views despite the original transactions
 * already being completed.
 *
 * <p>This filter makes Hibernate Sessions available via the current thread, which
 * will be autodetected by transaction managers. It is suitable for service layer
 * transactions via {@link org.springframework.orm.hibernate3.HibernateTransactionManager}
 * or {@link org.springframework.transaction.jta.JtaTransactionManager} as well
 * as for non-transactional execution (if configured appropriately).
 *
 * <p><b>NOTE</b>: This filter will by default <i>not</i> flush the Hibernate Session,
 * with the flush mode set to {@code FlushMode.NEVER}. It assumes to be used
 * in combination with service layer transactions that care for the flushing: The
 * active transaction manager will temporarily change the flush mode to
 * {@code FlushMode.AUTO} during a read-write transaction, with the flush
 * mode reset to {@code FlushMode.NEVER} at the end of each transaction.
 * If you intend to use this filter without transactions, consider changing
 * the default flush mode (through the "flushMode" property).
 *
 * <p><b>WARNING:</b> Applying this filter to existing logic can cause issues that
 * have not appeared before, through the use of a single Hibernate Session for the
 * processing of an entire request. In particular, the reassociation of persistent
 * objects with a Hibernate Session has to occur at the very beginning of request
 * processing, to avoid clashes with already loaded instances of the same objects.
 *
 * <p>Alternatively, turn this filter into deferred close mode, by specifying
 * "singleSession"="false": It will not use a single session per request then,
 * but rather let each data access operation or transaction use its own session
 * (like without Open Session in View). Each of those sessions will be registered
 * for deferred close, though, actually processed at request completion.
 *
 * <p>A single session per request allows for most efficient first-level caching,
 * but can cause side effects, for example on {@code saveOrUpdate} or when
 * continuing after a rolled-back transaction. The deferred close strategy is as safe
 * as no Open Session in View in that respect, while still allowing for lazy loading
 * in views (but not providing a first-level cache for the entire request).
 *
 * <p>Looks up the SessionFactory in Spring's root web application context.
 * Supports a "sessionFactoryBeanName" filter init-param in {@code web.xml};
 * the default bean name is "sessionFactory". Looks up the SessionFactory on each
 * request, to avoid initialization order issues (when using ContextLoaderServlet,
 * the root application context will get initialized <i>after</i> this filter).
 *
 * @author Juergen Hoeller
 * @since 1.2
 * @see #setSingleSession
 * @see #setFlushMode
 * @see #lookupSessionFactory
 * @see OpenSessionInViewInterceptor
 * @see org.springframework.orm.hibernate3.HibernateInterceptor
 * @see org.springframework.orm.hibernate3.HibernateTransactionManager
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession
 * @see org.springframework.transaction.support.TransactionSynchronizationManager
 */
public class OpenSessionInViewFilter extends OncePerRequestFilter {

	public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME = "sessionFactory";


	private String sessionFactoryBeanName = DEFAULT_SESSION_FACTORY_BEAN_NAME;

	private boolean singleSession = true;

	private FlushMode flushMode = FlushMode.MANUAL;


	/**
	 * Set the bean name of the SessionFactory to fetch from Spring's
	 * root application context. Default is "sessionFactory".
	 * @see #DEFAULT_SESSION_FACTORY_BEAN_NAME
	 */
	public void setSessionFactoryBeanName(String sessionFactoryBeanName) {
		this.sessionFactoryBeanName = sessionFactoryBeanName;
	}

	/**
	 * Return the bean name of the SessionFactory to fetch from Spring's
	 * root application context.
	 */
	protected String getSessionFactoryBeanName() {
		return this.sessionFactoryBeanName;
	}

	/**
	 * Set whether to use a single session for each request. Default is "true".
	 * <p>If set to "false", each data access operation or transaction will use
	 * its own session (like without Open Session in View). Each of those
	 * sessions will be registered for deferred close, though, actually
	 * processed at request completion.
	 * @see SessionFactoryUtils#initDeferredClose
	 * @see SessionFactoryUtils#processDeferredClose
	 */
	public void setSingleSession(boolean singleSession) {
		this.singleSession = singleSession;
	}

	/**
	 * Return whether to use a single session for each request.
	 */
	protected boolean isSingleSession() {
		return this.singleSession;
	}

	/**
	 * Specify the Hibernate FlushMode to apply to this filter's
	 * {@link org.hibernate.Session}. Only applied in single session mode.
	 * <p>Can be populated with the corresponding constant name in XML bean
	 * definitions: e.g. "AUTO".
	 * <p>The default is "MANUAL". Specify "AUTO" if you intend to use
	 * this filter without service layer transactions.
	 * @see org.hibernate.Session#setFlushMode
	 * @see org.hibernate.FlushMode#MANUAL
	 * @see org.hibernate.FlushMode#AUTO
	 */
	public void setFlushMode(FlushMode flushMode) {
		this.flushMode = flushMode;
	}

	/**
	 * Return the Hibernate FlushMode that this filter applies to its
	 * {@link org.hibernate.Session} (in single session mode).
	 */
	protected FlushMode getFlushMode() {
		return this.flushMode;
	}

	/**
	 * The default value is "false" so that the filter may re-bind the opened
	 * {@code Session} to each asynchronously dispatched thread and postpone
	 * closing it until the very last asynchronous dispatch.
	 */
	@Override
	protected boolean shouldNotFilterAsyncDispatch() {
		return false;
	}

	/**
	 * Returns "false" so that the filter may provide a Hibernate
	 * {@code Session} to each error dispatches.
	 */
	@Override
	protected boolean shouldNotFilterErrorDispatch() {
		return false;
	}

	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		SessionFactory sessionFactory = lookupSessionFactory(request);
		boolean participate = false;

		WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
		String key = getAlreadyFilteredAttributeName();

		if (isSingleSession()) {
			// single session mode
			if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
				// Do not modify the Session: just set the participate flag.
				participate = true;
			}
			else {
				boolean isFirstRequest = !isAsyncDispatch(request);
				if (isFirstRequest || !applySessionBindingInterceptor(asyncManager, key)) {
					logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
					Session session = getSession(sessionFactory);
					SessionHolder sessionHolder = new SessionHolder(session);
					TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);

					asyncManager.registerCallableInterceptor(key,
							new SessionBindingCallableInterceptor(sessionFactory, sessionHolder));
				}
			}
		}
		else {
			// deferred close mode
			Assert.state(!isAsyncStarted(request), "Deferred close mode is not supported on async dispatches");
			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
					SessionHolder sessionHolder =
							(SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
					if (!isAsyncStarted(request)) {
						logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
						closeSession(sessionHolder.getSession(), sessionFactory);
					}
				}
				else {
					// deferred close mode
					SessionFactoryUtils.processDeferredClose(sessionFactory);
				}
			}
		}
	}

	/**
	 * Look up the SessionFactory that this filter should use,
	 * taking the current HTTP request as argument.
	 * <p>The default implementation delegates to the {@link #lookupSessionFactory()}
	 * variant without arguments.
	 * @param request the current request
	 * @return the SessionFactory to use
	 */
	protected SessionFactory lookupSessionFactory(HttpServletRequest request) {
		return lookupSessionFactory();
	}

	/**
	 * Look up the SessionFactory that this filter should use.
	 * <p>The default implementation looks for a bean with the specified name
	 * in Spring's root application context.
	 * @return the SessionFactory to use
	 * @see #getSessionFactoryBeanName
	 */
	protected SessionFactory lookupSessionFactory() {
		if (logger.isDebugEnabled()) {
			logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
		}
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
	}

	/**
	 * Get a Session for the SessionFactory that this filter uses.
	 * Note that this just applies in single session mode!
	 * <p>The default implementation delegates to the
	 * {@code SessionFactoryUtils.getSession} method and
	 * sets the {@code Session}'s flush mode to "MANUAL".
	 * <p>Can be overridden in subclasses for creating a Session with a
	 * custom entity interceptor or JDBC exception translator.
	 * @param sessionFactory the SessionFactory that this filter uses
	 * @return the Session to use
	 * @throws DataAccessResourceFailureException if the Session could not be created
	 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
	 * @see org.hibernate.FlushMode#MANUAL
	 */
	protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
		Session session = SessionFactoryUtils.getSession(sessionFactory, true);
		FlushMode flushMode = getFlushMode();
		if (flushMode != null) {
			session.setFlushMode(flushMode);
		}
		return session;
	}

	/**
	 * Close the given Session.
	 * Note that this just applies in single session mode!
	 * <p>Can be overridden in subclasses, e.g. for flushing the Session before
	 * closing it. See class-level javadoc for a discussion of flush handling.
	 * Note that you should also override getSession accordingly, to set
	 * the flush mode to something else than NEVER.
	 * @param session the Session used for filtering
	 * @param sessionFactory the SessionFactory that this filter uses
	 */
	protected void closeSession(Session session, SessionFactory sessionFactory) {
		SessionFactoryUtils.closeSession(session);
	}

	private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) {
		if (asyncManager.getCallableInterceptor(key) == null) {
			return false;
		}
		((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread();
		return true;
	}


	/**
	 * Bind and unbind the Hibernate {@code Session} to the current thread.
	 */
	private static class SessionBindingCallableInterceptor extends CallableProcessingInterceptorAdapter {

		private final SessionFactory sessionFactory;

		private final SessionHolder sessionHolder;

		public SessionBindingCallableInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) {
			this.sessionFactory = sessionFactory;
			this.sessionHolder = sessionHolder;
		}

		@Override
		public <T> void preProcess(NativeWebRequest request, Callable<T> task) {
			initializeThread();
		}

		@Override
		public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
			TransactionSynchronizationManager.unbindResource(this.sessionFactory);
		}

		private void initializeThread() {
			TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder);
		}
	}

}
0
6
分享到:
评论

相关推荐

    关于OpenSessionInViewFilter的学习

    NULL 博文链接:https://yanzhenwei.iteye.com/blog/1701164

    SSH项目整合示例【OpenSessionInView】所用到的jar包

    SSH项目整合示例【OpenSessionInView】所用到的jar包 包含Struts + Hibernate + Spring所有jar及其依赖的jar

    jar包(struts2.0.8+spring2.0+hibernate3.2)

    struts2.0.8+spring2.0+hibernate3.2 jar包

    SPRING API 2.0.CHM

    OpenSessionInViewFilter OpenSessionInViewInterceptor OpenSessionInViewInterceptor OptimisticLockingFailureException OptionsTag OptionTag OptionWriter OracleLobHandler OracleLobHandler....

    OA项目SSH整合框架

    &lt;filter-class&gt;org.springframework.orm.hibernate3.support.OpenSessionInViewFilter &lt;filter-name&gt;OpenSessionInView *.do 2,LazyInitializationException异常说明 1,对于集合属性...

    Sping 事务管理.doc

    OpenSessionInViewFilter解决Web应用程序的问题

    spring_demo:Spring MVC示范项目

    Spring MVC Hibernate Demo Hibernate 配置 数据库实体必须设置以下注解 @Entity ... &lt;filter&gt;org.springframework.orm.hibernate4.support.OpenSessionInViewFilter &lt;param&gt;flushMode&lt;/param-nam

    S2SH集成 案例

    该案例实现了一个简单的登录功能,但里面将S2SH集成的所有配置信息都添加进去了。 如,OpenSessionInViewFilter、声明式事务、三层等等

    spring_note.rar_inversion_spring concept

    课程内容 面向接口(抽象)编程的概念与好处 IOC/DI的概念与好处 inversion of control dependency injection AOP的概念与好处 ...opensessionInviewfilter(记住,解决什么问题,怎么解决) Spring JDBC

    struts+spring+hibernate整合

    Spring4.0、Struts2.3.15、Hibernate4.2.4、jQuery1.9.1涉及到了诸多开发时的细节:ModelDriven、Preparable 拦截器、编写自定义的类型转换器、Struts2 处理 Ajax、OpenSessionInViewFilter、迫切左外连接、Spring ...

    Mac Mysql数据库中文乱码问题解决

    Mac 下MySQL数据库中文乱码解决方案: 当我们用框架进行数据库的存储操作时,经常会遇到中文乱码...-- 表单处理乱码,必须在OpenSessionInViewFilter的filter之前 --&gt; &lt;filter&gt;CharacterFilter &lt;filter&gt;org.sprin

Global site tag (gtag.js) - Google Analytics