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

HibernateInterceptor

 
阅读更多
继承HibernateAccessor功能,在代理到Hibernate操作之前尚未发现Session则创建绑定,否则使用线程已绑定的Session;操作中出现错误可开启exceptionConversionEnabled以转换异常;操作结束后,Session由自己创建则关闭或延迟关闭,否则回复FlushMode

/*
 * 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;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * This interceptor binds a new Hibernate Session to the thread before a method
 * call, closing and removing it afterwards in case of any method outcome.
 * If there already is a pre-bound Session (e.g. from HibernateTransactionManager,
 * or from a surrounding Hibernate-intercepted method), the interceptor simply
 * participates in it.
 *
 * <p>Application code must retrieve a Hibernate Session via the
 * {@code SessionFactoryUtils.getSession} method or - preferably -
 * Hibernate's own {@code SessionFactory.getCurrentSession()} method, to be
 * able to detect a thread-bound Session. Typically, the code will look like as follows:
 *
 * <pre>
 * public void doSomeDataAccessAction() {
 *   Session session = this.sessionFactory.getCurrentSession();
 *   ...
 *   // No need to close the Session or translate exceptions!
 * }</pre>
 *
 * Note that this interceptor automatically translates HibernateExceptions,
 * via delegating to the {@code SessionFactoryUtils.convertHibernateAccessException}
 * method that converts them to exceptions that are compatible with the
 * {@code org.springframework.dao} exception hierarchy (like HibernateTemplate does).
 * This can be turned off if the raw exceptions are preferred.
 *
 * <p>This class can be considered a declarative alternative to HibernateTemplate's
 * callback approach. The advantages are:
 * [list]
 * <li>no anonymous classes necessary for callback implementations;
 * <li>the possibility to throw any application exceptions from within data access code.
 * [/list]
 *
 * <p>The drawback is the dependency on interceptor configuration. However, note
 * that this interceptor is usually <i>not</i> necessary in scenarios where the
 * data access code always executes within transactions. A transaction will always
 * have a thread-bound Session in the first place, so adding this interceptor to the
 * configuration just adds value when fine-tuning Session settings like the flush mode
 * - or when relying on exception translation.
 *
 * @author Juergen Hoeller
 * @since 1.2
 * @see org.hibernate.SessionFactory#getCurrentSession()
 * @see HibernateTransactionManager
 * @see HibernateTemplate
 */
public class HibernateInterceptor extends HibernateAccessor implements MethodInterceptor {

	private boolean exceptionConversionEnabled = true;


	/**
	 * Set whether to convert any HibernateException raised to a Spring DataAccessException,
	 * compatible with the {@code org.springframework.dao} exception hierarchy.
	 * <p>Default is "true". Turn this flag off to let the caller receive raw exceptions
	 * as-is, without any wrapping.
	 * @see org.springframework.dao.DataAccessException
	 */
	public void setExceptionConversionEnabled(boolean exceptionConversionEnabled) {
		this.exceptionConversionEnabled = exceptionConversionEnabled;
	}


	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		Session session = getSession();
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());

		boolean existingTransaction = (sessionHolder != null && sessionHolder.containsSession(session));
		if (existingTransaction) {
			logger.debug("Found thread-bound Session for HibernateInterceptor");
		}
		else {
			if (sessionHolder != null) {
				sessionHolder.addSession(session);
			}
			else {
				TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
			}
		}

		FlushMode previousFlushMode = null;
		try {
			previousFlushMode = applyFlushMode(session, existingTransaction);
			enableFilters(session);
			Object retVal = methodInvocation.proceed();
			flushIfNecessary(session, existingTransaction);
			return retVal;
		}
		catch (HibernateException ex) {
			if (this.exceptionConversionEnabled) {
				throw convertHibernateAccessException(ex);
			}
			else {
				throw ex;
			}
		}
		finally {
			if (existingTransaction) {
				logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
				disableFilters(session);
				if (previousFlushMode != null) {
					session.setFlushMode(previousFlushMode);
				}
			}
			else {
				SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
				if (sessionHolder == null || sessionHolder.doesNotHoldNonDefaultSession()) {
					TransactionSynchronizationManager.unbindResource(getSessionFactory());
				}
			}
		}
	}

	/**
	 * Return a Session for use by this interceptor.
	 * @see SessionFactoryUtils#getSession
	 */
	protected Session getSession() {
		return SessionFactoryUtils.getSession(
				getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
	}

}
0
2
分享到:
评论

相关推荐

    HibernateInterceptor.java

    Hibernate4,Interceptor,spring,quartz

    Hibernate与struts2结合使用的demo

    编写HibernateInterceptor,负责开启和关闭Session,以及处理异常。 ```java public class HibernateInterceptor implements Interceptor { public void destroy() {} public void init() {} public String ...

    jpaprojections:示例项目演示了如何使用Hibernate Interceptor and Envers,DTO Projection,Observer和Command设计模式

    使用Hibernate拦截器检测Persistence Context中的实体更改 使用Hibernate拦截器对数据库中的实体更改做出React 使用观察者设计模式来监视实体持久性更改并对其做出React 使用命令设计模式提供一种通用方法,可将...

    Spring+Hibernate+Proxool连接池

    3. **使用HibernateTemplate或HibernateInterceptor**:Spring提供了HibernateTemplate或HibernateInterceptor,这两个工具类可以帮助我们更好地管理和控制Hibernate的操作,避免直接操作Session,降低出错的可能性...

    applicationContext.xml 详细配置

    &lt;bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor"&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; ...

    Spring2.5+Hibernate3整合

    6. **Hibernate Interceptor**:可以自定义拦截器,实现对 Hibernate 操作的扩展,如日志记录、性能监控等。 7. **AOP(Aspect Oriented Programming)**:Spring 的 AOP 功能可用于实现如日志、事务管理等横切关注...

    Spring对Hibernate及JDBC提供的支持

    Spring提供了HibernateTemplate和HibernateInterceptor等工具类,简化了事务管理,并且通过AOP(面向切面编程)实现了声明式事务,使得事务处理更加透明化。此外,Spring还允许我们方便地进行数据源配置,以及自动...

    Hibernate的高级操作

    - **HibernateInterceptor**:这是一个非常灵活的机制,允许在Hibernate内部操作的不同阶段进行拦截。通过实现`HibernateInterceptor`接口,开发者可以自定义拦截逻辑,例如日志记录、安全性检查等。 通过上述内容...

    spring-hibernate注解配置源码

    同时,`SessionFactory`和`Session`的创建可以通过`LocalSessionFactoryBean`和`HibernateTemplate`或`HibernateInterceptor`进行注解配置。 Struts2作为MVC框架,负责处理HTTP请求和响应。它的注解如`@Action`、`@...

    SpringMVC3 + Hibernate4 例子代码

    3. 配置HibernateTemplate或HibernateInterceptor:这两个是Spring提供的便捷工具,用于简化Hibernate操作。 4. 配置DAO(Data Access Object):创建DAO层,使用HibernateTemplate或Session来执行数据库操作。 5. ...

    Spring 中使用 Hibernate.docx

    我们可以使用`HibernateTemplate`或`HibernateInterceptor`进行进一步的数据访问操作。例如,使用`HibernateTemplate`: ```xml &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate5....

    SpringMVC+Hibernate用到的jar包

    2. 使用Spring的`HibernateTemplate`或`HibernateInterceptor`进行数据访问操作。 3. 将Hibernate的DAO层注入到Spring MVC的Controller中,实现业务逻辑。 4. 配置Spring的事务管理器,例如`...

    hibernate 整合spring

    2. **SessionFactory和Session的管理**:Spring通过`SessionFactoryBean`来配置和管理`SessionFactory`,并使用`HibernateTemplate`或`HibernateInterceptor`来管理`Session`,避免了手动创建和关闭`Session`可能...

    hibernate+spring所需包

    同时,它还提供了`HibernateTemplate`和`HibernateInterceptor`,帮助开发者更方便地操作Hibernate。 2. **Hibernate核心库**:这包括了Hibernate的主要API,如`Session`, `SessionFactory`, `Query`等,以及实体...

    SSH动态切换数据源

    而Hibernate则可以通过SessionFactory的getCurrentSession()方法,结合Spring的HibernateTemplate或HibernateInterceptor,确保每个数据库操作都在正确的数据源上下文中进行。 为了便于理解和实践,示例压缩包可能...

    ssh整合+oracle所用 jar包

    5. 在Struts2中配置Hibernate插件,如Hibernate Interceptor,以支持事务管理。 在实际开发中,还需要考虑异常处理、安全性、性能优化等方面的问题。例如,使用AOP进行异常统一处理,利用缓存提高数据读取效率,...

    官方原版源码spring-framework-5.0.14.RELEASE.zip

    在源码中,`JdbcTemplate`和`SimpleJdbcInsert`是简化JDBC操作的工具类,而`HibernateTemplate`和`HibernateInterceptor`则提供了对Hibernate的支持。 除了以上核心模块,Spring Framework 5.0.14.RELEASE还包含了...

    spring 源码解析

    `JdbcTemplate`和`SimpleJdbcInsert`简化了JDBC操作,`HibernateTemplate`和`HibernateInterceptor`提供了对Hibernate的支持。 10. **Spring Boot**:Spring Boot简化了Spring应用的启动和配置。`SpringApplication...

Global site tag (gtag.js) - Google Analytics