Sealyu

--- 博客已迁移至: http://www.sealyu.com/blog

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  618 随笔 :: 87 文章 :: 225 评论 :: 0 Trackbacks

Spring+Hibernate做项目, 发现有member在不加事务的情况下就去调用 getSession() 方法, 结果导致数据库连接不能释放, 也无法正常的提交事务(只能做查询, 不能做save(), update()). 如果配合连接池使用的话, 不出几分钟就会导致连接池无法拿到新连接的情况.

不过, 只要给DAO或者Service加入了事务, 就不会出现连接泄漏的问题.

谈谈解决方案:

最佳方案: 加入事务, 例如 tx 标签或者 @Transactional 都可以.

最笨方案: 修改代码, 使用 HibernateTemplate 来完成相关操作:

       public List queryAll( final String hql, final Object... args) {

              List list = getHibernateTemplate().executeFind( new HibernateCallback() {

                       public Object doInHibernate(Session session)

                       throws HibernateException, SQLException {

                      Query query = session.createQuery(hql);

                      

                       for ( int i =0; i < args. length ; i++) {

                             query.setParameter(i, args[i]);

                      }

                      

 

                      List list = query.list();

                       return list;

                      }

                     });

                           

              return list;        

       }

       public Serializable save(Object entity) {

              return getHibernateTemplate().save(entity);

       }

 

HibernateDaoSupport 代码里面的原始说明文档指出直接调用getSession()方法必须用配套的releaseSession(Session session)来释放连接, 根据我的测试, 就算配置了 OpenSessionInViewFilter(前提: 不加事务), 也不会关闭这个Session. 也许有人说可以用连接池, 这种情况和Db pool没关系, 用了pool就会发现连接很快就会满, 只会over的更快.  反过来, 如果不配置OpenSessionInViewFilter, 在DAO里提前用 releaseSession()关闭连接, 就可能会在JSP中出现Lazy载入异常. 另一个不配事务的问题就是无法更新或者插入数据. 下面就是原始的JavaDoc中的说明:

       /**

         * Obtain a Hibernate Session, either from the current transaction or

         * a new one. The latter is only allowed if the

         * {@link org.springframework.orm.hibernate3.HibernateTemplate#setAllowCreate "allowCreate"}

         * setting of this bean's {@link #setHibernateTemplate HibernateTemplate} is "true".

         * <p><b> Note that this is not meant to be invoked from HibernateTemplate code

         * but rather just in plain Hibernate code. </b> Either rely on a thread - bound

         * Session or use it in combination with {@link #releaseSession} .

         * <p> In general, it is recommended to use HibernateTemplate, either with

         * the provided convenience operations or with a custom HibernateCallback

         * that provides you with a Session to work on. HibernateTemplate will care

         * for all resource management and for proper exception conversion.

         * @return the Hibernate Session

         * @throws DataAccessResourceFailureException if the Session couldn't be created

         * @throws IllegalStateException if no thread - bound Session found and allowCreate=false

         * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)

         */

       protected final Session getSession()

           throws DataAccessResourceFailureException, IllegalStateException {

 

              return getSession( this . hibernateTemplate .isAllowCreate());

       }

 

       /**

         * Close the given Hibernate Session, created via this DAO's SessionFactory,

         * if it isn't bound to the thread (i.e. isn't a transactional Session).

         * <p> Typically used in plain Hibernate code, in combination with

         * {@link #getSession} and {@link #convertHibernateAccessException} .

         * @param session the Session to close

         * @see org.springframework.orm.hibernate3.SessionFactoryUtils#releaseSession

         */

       protected final void releaseSession(Session session) {

              SessionFactoryUtils.releaseSession(session, getSessionFactory());

       }

 

 

 HibernateDaoSupport用ThreadLocal保存Session列表并编写一个配套的过滤器来显式关闭Session, 并在关闭之前尝试提交事务. 下面是重写的 HibernateDaoSupport 代码:

 

						package org.springframework.orm.hibernate3.support;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.support.DaoSupport;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;


/**
* 修改后的避免连接泄漏的 HibernateDaoSupport, 多连接版本, 不保证跨DAO的事务.
*
* @author 刘长炯
* Date: 2009-3-11
*/
publicabstractclass HibernateDaoSupport extends DaoSupport {
/** 使用 ThreadLocal 保存打开的 Session 列表 */
privatestaticfinal ThreadLocal< List<Session> > sessions = new ThreadLocal< List<Session> >();

/**
* 获取Hibernate连接.
* @return
*/
publicstatic List<Session> getSessionList() {
//1. 先看看是否有了List get()
List list = sessions.get();
// 2. 没有的话从创建一个, put()
if(list == null) {
list = new ArrayList();
sessions.set(list);
}
// 3. 返回 Session
return list;
}

/**
* 关闭当前线程中未正常释放的 Session.
*/
publicstaticvoid closeSessionList() {
// 1. 先看看是否有了List get()
List<Session> list = sessions.get();
// 2. 有的话就直接关闭
if(list != null) {
System.out.println(SimpleDateFormat.getDateTimeInstance().format(new java.util.Date()) +
" -------- 即将释放未正常关闭的 Session");


for(Session session : list) {
System.out.println("正在关闭 session =" + session.hashCode());
// ! 关闭前事务提交
if(session.isOpen()) {
try {
session.getTransaction().commit();
} catch(Exception ex) {
try {
session.getTransaction().rollback();
} catch (HibernateException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
try {
session.close();
} catch(Exception ex) {

}

}
//releaseSession(session); // 无法调用
}
sessions.remove();
}

}

private HibernateTemplate hibernateTemplate;


/**
* Set the Hibernate SessionFactory to be used by this DAO.
* Will automatically create a HibernateTemplate for the given SessionFactory.
* @see #createHibernateTemplate
* @see #setHibernateTemplate
*/
publicfinalvoid setSessionFactory(SessionFactory sessionFactory) {
if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {
this.hibernateTemplate = createHibernateTemplate(sessionFactory);
}
}

/**
* Create a HibernateTemplate for the given SessionFactory.
* Only invoked if populating the DAO with a SessionFactory reference!
* <p>Can be overridden in subclasses to provide a HibernateTemplate instance
* with different configuration, or a custom HibernateTemplate subclass.
* @param sessionFactory the Hibernate SessionFactory to create a HibernateTemplate for
* @return the new HibernateTemplate instance
* @see #setSessionFactory
*/
protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
returnnew HibernateTemplate(sessionFactory);
}

/**
* Return the Hibernate SessionFactory used by this DAO.
*/
publicfinal SessionFactory getSessionFactory() {
return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null);
}

/**
* Set the HibernateTemplate for this DAO explicitly,
* as an alternative to specifying a SessionFactory.
* @see #setSessionFactory
*/
publicfinalvoid setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}

/**
* Return the HibernateTemplate for this DAO,
* pre-initialized with the SessionFactory or set explicitly.
* <p><b>Note: The returned HibernateTemplate is a shared instance.</b>
* You may introspect its configuration, but not modify the configuration
* (other than from within an {@link #initDao} implementation).
* Consider creating a custom HibernateTemplate instance via
* <code>new HibernateTemplate(getSessionFactory())</code>, in which
* case you're allowed to customize the settings on the resulting instance.
*/
publicfinal HibernateTemplate getHibernateTemplate() {
returnthis.hibernateTemplate;
}

protectedfinalvoid checkDaoConfig() {
if (this.hibernateTemplate == null) {
thrownew IllegalArgumentException("'sessionFactory' or 'hibernateTemplate' is required");
}
}


/**
* Obtain a Hibernate Session, either from the current transaction or
* a new one. The latter is only allowed if the
* {@link org.springframework.orm.hibernate3.HibernateTemplate#setAllowCreate "allowCreate"}
* setting of this bean's {@link #setHibernateTemplate HibernateTemplate} is "true".
* <p><b>Note that this is not meant to be invoked from HibernateTemplate code
* but rather just in plain Hibernate code.</b> Either rely on a thread-bound
* Session or use it in combination with {@link #releaseSession}.
* <p>In general, it is recommended to use HibernateTemplate, either with
* the provided convenience operations or with a custom HibernateCallback
* that provides you with a Session to work on. HibernateTemplate will care
* for all resource management and for proper exception conversion.
* @return the Hibernate Session
* @throws DataAccessResourceFailureException if the Session couldn't be created
* @throws IllegalStateException if no thread-bound Session found and allowCreate=false
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
*/
protectedfinal Session getSession()
throws DataAccessResourceFailureException, IllegalStateException {
Session session = getSession(this.hibernateTemplate.isAllowCreate());

// 开始事务
try {
session.beginTransaction();
} catch (HibernateException e) {
e.printStackTrace();
}

getSessionList().add(session);

return session;
}

/**
* Obtain a Hibernate Session, either from the current transaction or
* a new one. The latter is only allowed if "allowCreate" is true.
* <p><b>Note that this is not meant to be invoked from HibernateTemplate code
* but rather just in plain Hibernate code.</b> Either rely on a thread-bound
* Session or use it in combination with {@link #releaseSession}.
* <p>In general, it is recommended to use
* {@link #getHibernateTemplate() HibernateTemplate}, either with
* the provided convenience operations or with a custom
* {@link org.springframework.orm.hibernate3.HibernateCallback} that
* provides you with a Session to work on. HibernateTemplate will care
* for all resource management and for proper exception conversion.
* @param allowCreate if a non-transactional Session should be created when no
* transactional Session can be found for the current thread
* @return the Hibernate Session
* @throws DataAccessResourceFailureException if the Session couldn't be created
* @throws IllegalStateException if no thread-bound Session found and allowCreate=false
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
*/
protectedfinal Session getSession(boolean allowCreate)
throws DataAccessResourceFailureException, IllegalStateException {

return (!allowCreate ?
SessionFactoryUtils.getSession(getSessionFactory(), false) :
SessionFactoryUtils.getSession(
getSessionFactory(),
this.hibernateTemplate.getEntityInterceptor(),
this.hibernateTemplate.getJdbcExceptionTranslator()));
}

/**
* Convert the given HibernateException to an appropriate exception from the
* <code>org.springframework.dao</code> hierarchy. Will automatically detect
* wrapped SQLExceptions and convert them accordingly.
* <p>Delegates to the
* {@link org.springframework.orm.hibernate3.HibernateTemplate#convertHibernateAccessException}
* method of this DAO's HibernateTemplate.
* <p>Typically used in plain Hibernate code, in combination with
* {@link #getSession} and {@link #releaseSession}.
* @param ex HibernateException that occured
* @return the corresponding DataAccessException instance
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#convertHibernateAccessException
*/
protectedfinal DataAccessException convertHibernateAccessException(HibernateException ex) {
returnthis.hibernateTemplate.convertHibernateAccessException(ex);
}

/**
* Close the given Hibernate Session, created via this DAO's SessionFactory,
* if it isn't bound to the thread (i.e. isn't a transactional Session).
* <p>Typically used in plain Hibernate code, in combination with
* {@link #getSession} and {@link #convertHibernateAccessException}.
* @param session the Session to close
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#releaseSession
*/
protectedfinalvoid releaseSession(Session session) {
SessionFactoryUtils.releaseSession(session, getSessionFactory());
}

}
用这个类来覆盖Spring内置的那个HibernateDaoSupport, 然后随便编写一个过滤器, 如下所示:
						public
void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {

req.setCharacterEncoding(this.charset);
chain.doFilter(req, res);
// 关闭遗漏的 Session
HibernateDaoSupport.closeSessionList();
}


把这个过滤器配置在过滤器链的第一个, 就OK了.

最 后也许会有人说, 为什么不用tx标签在Spring中来配置一个通配符就全部加入了事务了呢? 不过很遗憾, 经测试发现此方式无法实现跨DAO的Hibernate事务, 所以只好很无奈的放弃了这种方式. 这就是文章一开头提到的最佳方案, 也许是成本最低的方案了, 但是我却没采用, 一是因为事务问题, 二是因为每个有问题的dao/service包都要修改一次XML配置文件, 我很懒惰, 不想去看那些代码都在哪些包里面. Tx标签的配置方式如下所示:

						<?
xml
version
="1.0"
encoding
="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
>

<beanid="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<propertyname="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>

<beanid="StudentDAO"class="dao.StudentDAO">
<propertyname="sessionFactory">
<refbean="sessionFactory"/>
</property>
</bean>

<!-- 声明一个 Hibernate 3 的 事务管理器供代理类自动管理事务用 -->
<beanid="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<propertyname="sessionFactory">
<reflocal="sessionFactory"/>
</property>
</bean>

<aop:config>
<!-- 切入点指明了在执行dao.StudentDAO的所有方法时产生事务拦截操作 -->
<aop:pointcutid="daoMethods"
expression="execution(* dao.StudentDAO.*(..))"/>
<!-- 定义了将采用何种拦截操作,这里引用到 txAdvice -->
<aop:advisoradvice-ref="txAdvice"
pointcut-ref="daoMethods"/>
</aop:config>

<!-- 这是事务通知操作,使用的事务管理器引用自 transactionManager -->
<tx:adviceid="txAdvice"transaction-manager="transactionManager">
<tx:attributes>
<!-- 指定哪些方法需要加入事务,这里懒惰一下全部加入,可以使用通配符来只加入需要的方法 -->
<tx:methodname="*"propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>

</beans>

其它加事务的方式有老式的Spring1.2的, 还有Annotation的, 这些都是一个解决方案, 就是给DAO/Service加入事务. 如果您有更好的办法, 欢迎来信探讨.

posted on 2010-02-22 16:43 seal 阅读(2276) 评论(0)  编辑  收藏 所属分类: SpringHibernate

只有注册用户登录后才能发表评论。


网站导航: