- 浏览: 338519 次
- 性别:
- 来自: 深圳
文章分类
最新评论
-
zuoguoyao:
版主,有没有 ext数据互动的。。教程
Ext2.0教程一:Ext介绍以及 ext页面布局 -
NineInchNails:
谢谢分享:D
Ext2.0教程一:Ext介绍以及 ext页面布局 -
风雨故都:
liuming
ext 多文件上传控件 Ext.ux.UploadDialog 使用中的问题 -
yanjiarui:
下必须能下,就是卡了点
oracle11g下载Oracle 10g下载 Oracle 9i 下载 -
coolbaby1984514:
public int findMonkey(int n, in ...
约瑟夫问题 java
假设在你的应用中Hibernate是通过spring 来管理它的session.如果在你的应用中没有使用OpenSessionInViewFilter或者OpenSessionInViewInterceptor。session会在transaction结束后关闭。
如果你采用了spring的声明式事务模式,它会对你的被代理对象的每一个方法进行事务包装(AOP的方式)。如下:
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="manager" parent="txProxyTemplate">
<property name="target">
<bean class="org.appfuse.service.impl.BaseManager">
<property name="dao" ref="dao"/>
</bean>
</property>
</bean>
目标类org.appfuse.service.impl.BaseManager 的 save *方法的事务类型PROPAGATION_REQUIRED ,remove* 方法的事务类型PROPAGATION_REQUIRED
其他的方法的事务类型是PROPAGATION_REQUIRED,readOnly。
所以给你的感觉是调用这个名为“manager”的bean的方法之后session就关掉了。
如果应用中使用了OpenSessionInViewFilter或者OpenSessionInViewInterceptor,所有打开的session会被保存在一个线程变量里。在线程退出前通过
OpenSessionInViewFilter或者OpenSessionInViewInterceptor断开这些session。 为什么这么做?这主要是为了实现Hibernate的延迟加载功能。基于一个请求
一个hibernate session的原则。
spring中对OpenSessionInViewFilter的描述如下:
它是一个Servlet2.3过滤器,用来把一个Hibernate Session和一次完整的请求过程对应的线程相绑定。目的是为了实现"Open Session in View"的模式。
例如: 它允许在事务提交之后延迟加载显示所需要的对象。
这个过滤器和 HibernateInterceptor 有点类似:它是通过线程实现的。无论是没有事务的应用,还是有业务层事务的应用(通过HibernateTransactionManager 或
JtaTransactionManager的方式实现)它都适用。在后一种情况下,事务会自动采用由这个filter绑定的Session来进行相关的操作以及根据实际情况完成提交操作。
警告: 如果在你的应用中,一次请求的过程中使用了单一的一个HIbernate Session,在这种情况下,采用这个filter会产生一些以前没遇到的问题。特别需要注意的是通过
Hibernate Session重新组织持久化对象之间关系的相关操作需要在请求的最开始进行。以免与已经加载的相同对象发生冲突。
或者,我们可以通过指定"singleSession"="false"的方式把这个过滤器调到延期关闭模式。这样在一次请求的过程中不会使用一个单一的Session.每一次数据访问或事务相关
操作都使用属于它自己的session(有点像不使用Open Session in View).这些session都被注册成延迟关闭模式,即使是在这一次的请求中它相关操作已经完成。
"一次请求一个session" 对于一级缓存而言很有效,但是这样可以带来副作用。例如在saveOrUpdate的时候或事物回滚之后,虽然它和“no Open Session in View”同样安全。
但是它却允许延迟加载。
它会在spring的web应用的上下文根中查找Session工厂。它也支持通过在web.xml中定义的“SessionFactoryBeanName”的init-param元素 指定的Session工厂对应的bean的
名字来查找session工厂。默认的bean的名字是"sessionFactory".他通过每一次请求查找一次SessionFactory的方式来避免由初始化顺序引起的问题(当使用ContextLoaderServlet
来集成spring的时候 ,spring 的应用上下文是在这个filter 之后才被初始化的)。
默认的情况下,这个filter 不会同步Hibernate Session.这是因为它认为这项工作是通过业务层的事务来完成的。而且HibernateAccessors 的FlushMode为FLUSH_EAGER.如果你
想让这个filter在请求完成以后同步session.你需要覆盖它的closeSession方法,在这个方法中在调用父类的关闭session操作之前同步session.此外你需要覆盖它的getSession()
方法。返回一个session它的FlushMode 不是默认的FlushMode.NEVER。需要注意的是getSession()和closeSession()方法只有在single session的模式中才被调用。
在myfaces的wiki里提供了OpenSessionInViewFilter的一个子类如下:
public class OpenSessionInViewFilter extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter {
/**
* we do a different flushmode than in the codebase
* here
*/
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.COMMIT);
return session;
}
/**
* we do an explicit flush here just in case
* we do not have an automated flush
*/
protected void closeSession(Session session, SessionFactory factory) {
session.flush();
super.closeSession(session, factory);
}
}
附加源码 OpenSessionInViewFilter 代码 :
/*
* Copyright 2002-2007 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 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.web.context.WebApplicationContext;
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</code>. 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</code> during a read-write transaction, with the flush
* mode reset to <code>FlushMode.NEVER</code> 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</code> 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</code>;
* 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.NEVER;
/**
* 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 "NEVER". Specify "AUTO" if you intend to use
* this filter without service layer transactions.
* @see org.hibernate.Session#setFlushMode
* @see org.hibernate.FlushMode#NEVER
* @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;
}
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
SessionFactory sessionFactory = lookupSessionFactory(request);
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 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
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
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>Default implementation delegates to the <code>lookupSessionFactory</code>
* without arguments.
* @return the SessionFactory to use
* @see #lookupSessionFactory()
*/
protected SessionFactory lookupSessionFactory(HttpServletRequest request) {
return lookupSessionFactory();
}
/**
* Look up the SessionFactory that this filter should use.
* <p>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 (SessionFactory) 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</code> method and
* sets the <code>Session</code>'s flush mode to "NEVER".
* <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#NEVER
*/
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);
}
}
发表评论
-
Spring Security 2.0 安全框架 使用及文件配置说明
2009-03-13 10:00 3321Spring Security 2.0 安全框架使用说明 结合 ... -
Spring框架下获取Bean的几种方式
2008-05-09 09:47 4321通过xml配置文件 bean配置在xml里面,spr ... -
hibernate里load和get方法的区别详述
2008-06-26 17:12 1550A: Hibernate中有两个极为相似的方法get()与l ... -
Hibernate的get和load的区别
2008-04-19 13:28 1253load()方法是假定你所读取的对象是肯定存在的...而get ... -
Hibernate中自带ID的generator的含义
2008-04-19 13:29 14681、identity:用于MySql数据库。特点:递增 < ... -
典型的applicationContext.xml 配置
2008-04-19 13:35 1221<?xml version="1.0" ... -
Struts+Spring+Hibernate实现上传下载
2008-04-19 13:36 1169... -
扩展HibernateTemplate,实现分页查询 (回调)
2008-04-19 13:18 2265/*** 使用hql 语句进行操作* @param hql* ...
相关推荐
OpenSessionInViewFilter是Spring框架中一个非常重要的组件,主要用于解决数据访问...这个文档应该包含了OpenSessionInViewFilter的源码分析、配置示例以及常见问题的解答,对理解该过滤器的功能和工作原理非常有帮助。
OpenSessionInViewFilter个人学习总结
本资源主要讲解了Spring框架的基础概念和应用,涵盖了面向接口编程、IOC/DI、AOP、Spring应用IOC/DI、Spring应用AOP、Struts2.1.6 + Spring2.5.6 + Hibernate3.3.2整合、Spring JDBC面向接口编程等内容。 面向接口...
3. 在使用中如果遇到OpenSessionInView的问题,可以添加OpenSessionInViewFilter或OpenSessionInViewInterceptor。 五、Spring的事务管理 Spring框架提供了事务管理机制,提供了几个关于事务处理的类: 1. ...
- 在`web.xml`中配置`OpenSessionInViewFilter`过滤器,自动管理事务。 #### 三、总结 通过以上步骤,我们不仅可以让Spring有效地管理Struts,实现更灵活的业务逻辑控制,还可以利用Spring的强大功能管理...
Spring 框架是 Java 开发中的核心组件之一,它为开发者提供了许多强大的功能,包括依赖注入(DI)、控制反转(IOC)、事务管理以及对 ORM 框架的支持。以下是对这些知识点的详细解释: **1. Spring 的优点** - **...
Spring 框架是Java开发中的核心组件,它以其丰富的特性和灵活性深受开发者喜爱。面试中,Spring的相关问题经常出现,下面将详细解答这些常见面试题。 首先,Spring的优点包括: 1. 分层架构:Spring允许开发者选择...
- 利用CharacterEncodingFilter和OpenSessionInViewFilter解决编码问题。 通过以上内容的学习,开发者可以深入理解Spring 2.5的核心概念,掌握其在实际开发中的应用,从而提高工作效率和代码质量。
该模式的核心在于通过Spring提供的`OpenSessionInViewFilter`过滤器,在视图渲染过程中保持Hibernate Session的打开状态,从而简化了事务管理,并避免了一些常见的懒加载异常。 #### 一、OpenSessionInViewFilter...
Spring简介 Spring应用IOC/DI(重要) xml annotation Spring应用AOP(重要) xml annotation Struts2.1.6 + Spring2.5.6 + Hibernate3.3.2整合(重要) opensessionInviewfilter(记住,解决什么问题,怎么解决) ...
#### 三、Spring简介 **项目名称:** Spring_0200_IOC_Introduction **环境搭建:** - 只使用IoC功能的情况下,需要的jar包有: - `spring.jar` - `jakarta-commons/commons-logging.jar` **IoC容器:** - 实例...
同时,需要在Spring的配置文件(如applicationContext.xml)中定义Action及DAO实例,并指定相应的依赖注入。 3. Hibernate的配置文件(hibernate.cfg.xml)中,配置数据库连接、实体类映射等信息。Spring的配置文件...
### Struts2、Spring与Hibernate整合的关键点及注意事项 #### 一、概述 在Java Web开发领域,Struts2、Spring以及Hibernate是三个非常重要的框架。它们分别在MVC架构、依赖注入与业务逻辑管理、对象关系映射等方面...
【Struts、Spring与Hibernate集成】是Java Web开发中常见的技术组合,用于构建高效、松耦合的MVC应用程序。这三大框架的集成使得开发者能够更好地管理数据访问、业务逻辑和用户界面,提高代码的可维护性和可测试性。...
当遇到OpenSessionInView问题时,可以使用OpenSessionInViewFilter或OpenSessionInViewInterceptor来解决。 Spring的事务管理提供了强大且灵活的机制,主要包括编程式和声明式两种方式: 1. 编程式事务管理:通过...
Spring4.0、Struts2.3.15、Hibernate4.2.4、jQuery1.9.1涉及到了诸多开发时的细节:ModelDriven、Preparable 拦截器、编写自定义的类型转换器、Struts2 处理 Ajax、OpenSessionInViewFilter、迫切左外连接、Spring ...
解决这个问题的方法有两种:一种是在 web.xml 中使用 Spring 提供的 OpenSessionInViewFilter,另一种是在 application.xml 中配置 OpenSessionInViewFilter。前者通用,后者只能用于 SpringMVC 结构中。 最后,...
`@Resource` 默认按名称匹配,没有源码时,只能通过 XML 配置。 综上,Spring 框架通过提供强大的 IOC 和 AOP 功能,以及便捷的 XML 和注解配置,帮助开发者构建松散耦合、易于维护的 Java 应用。学习 Spring 不仅...