不过, 只要给DAO或者Service加入了事务, 就不会出现连接泄漏问题.
谈谈解决方案:
最佳方案: 加入事务, 例如 tx 标签或者 @Transactional 都可以.
最笨方案: 修改代码, 使用 HibernateTemplate 来完成相关操作:
public List queryAll( final String hql, final Object... args) {
List list = getHibernateTemplate.executeFind( HibernateCallback {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(hql);
for( i =0; i < args.length; i) {
query.Parameter(i, args[i]);
}
List list = query.list;
list;
}
});
list;
}
public Serializable save(Object entity) {
getHibernateTemplate.save(entity);
}
但是缺陷显而易见, 要有N多代码要进行改动.
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 _disibledevent=>
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
*/
protected final Session getSession
throws DataAccessResourceFailureException, IllegalStateException {
getSession(this.hibernateTemplate.isAllowCreate);
}
/**
* Close the given Hibernate Session, created via this DAO's SessionFactory,
* 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);
}
不需要改原始代码最终方案(方案 3):
不过, 如果项目里已经有了大量直接getSession而且没有加入事务配置代码(如历史原因导致), 这些代码太多, 没法修改, 那就最好寻求其它方案, 最好是不需要修改原来Java代码方案. 我采用这第 3个方案是重写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
*/
public abstract HibernateDaoSupport extends DaoSupport {
/** 使用 ThreadLocal 保存打开 Session 列表 */
private final ThreadLocal< List<Session> > sessions = ThreadLocal< List<Session> >;
/**
* 获取Hibernate连接.
* @
*/
public List<Session> getSessionList {
//1. 先看看是否有了List get
List list = sessions.get;
// 2. 没有话从创建个, put
(list null) {
list = ArrayList;
sessions.(list);
}
// 3. 返回 Session
list;
}
/**
* 关闭当前线程中未正常释放 Session.
*/
public void closeSessionList {
// 1. 先看看是否有了List get
List<Session> list = sessions.get;
// 2. 有话就直接关闭
(list != null) {
.out.prln(SimpleDateFormat.getDateTimeInstance.format( java.util.Date) +
" -------- 即将释放未正常关闭 Session");
for(Session session : list) {
.out.prln("正在关闭 session =" + session.hashCode);
// ! 关闭前事务提交
(session.isOpen) {
try {
session.getTransaction.commit;
} catch(Exception ex) {
try {
session.getTransaction.rollback;
} catch (HibernateException e) {
// TODO Auto-generated catch block
//e.prStackTrace;
}
}
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 #HibernateTemplate
*/
public final void SessionFactory(SessionFactory sessionFactory) {
(this.hibernateTemplate null || sessionFactory != this.hibernateTemplate.getSessionFactory) {
this.hibernateTemplate = createHibernateTemplate(sessionFactory);
}
}
/**
* Create a HibernateTemplate for the given SessionFactory.
* _disibledevent=> }
/**
* Set the HibernateTemplate for this DAO explicitly,
* as an alternative to specying a SessionFactory.
* @see #SessionFactory
*/
public final void HibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
/**
* Return the HibernateTemplate for this DAO,
* pre-initialized with the SessionFactory or explicitly.
* <p><b>Note: The ed HibernateTemplate is a shared instance.</b>
* You may rospect its configuration, but not mody the configuration
* (other than from within an {@link #initDao} implementation).
* Consider creating a custom HibernateTemplate instance via
* <code> HibernateTemplate(getSessionFactory)</code>, in which
* you're allowed to customize the tings _disibledevent=> throw IllegalArgumentException("'sessionFactory' or 'hibernateTemplate' is required");
}
}
/**
* Obtain a Hibernate Session, either from the current transaction or
* a _disibledevent=> * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
*/
protected final Session getSession
throws DataAccessResourceFailureException, IllegalStateException {
Session session = getSession(this.hibernateTemplate.isAllowCreate);
// 开始事务
try {
session.beginTransaction;
} catch (HibernateException e) {
e.prStackTrace;
}
getSessionList.add(session);
session;
}
/**
* Obtain a Hibernate Session, either from the current transaction or
* a _disibledevent=> * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
*/
protected final Session getSession(boolean allowCreate)
throws DataAccessResourceFailureException, IllegalStateException {
(!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
* @ the corresponding DataAccessException instance
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#convertHibernateAccessException
*/
protected final DataAccessException convertHibernateAccessException(HibernateException ex) {
this.hibernateTemplate.convertHibernateAccessException(ex);
}
/**
* Close the given Hibernate Session, created via this DAO's SessionFactory,
* 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);
}
}
用这个类来覆盖Spring内置那个HibernateDaoSupport, 然后随便编写个过滤器, 如下所示:
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
req.CharacterEncoding(this.char);
chain.doFilter(req, res);
// 关闭遗漏 Session
HibernateDaoSupport.closeSessionList;
}
把这个过滤器配置在过滤器链第个, 就OK了.
最后也许会有人说, 为什么不用tx标签在Spring中来配置个通配符就全部加入了事务了呢? 不过很遗憾, 经测试发现此方式无法实现跨DAOHibernate事务, 所以只好很无奈放弃了这种方式. 这就是文章开头提到最佳方案, 也许是成本最低方案了, 但是我却没采用, 是事务问题, 2是每个有问题dao/service包都要修改次XML配置文件, 我很懒惰, 不想去看那些代码都在哪些包里面. Tx标签配置方式如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">
<bean id="sessionFactory"
="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="path:hibernate.cfg.xml">
</property>
</bean>
<bean id="StudentDAO" ="dao.StudentDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- 声明个 Hibernate 3 事务管理器供代理类自动管理事务用 -->
<bean id="transactionManager"
="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<aop:config>
<!-- 切入点指明了在执行dao.StudentDAO所有思路方法时产生事务拦截操作 -->
<aop:pocut id="daoMethods"
expression="execution(* dao.StudentDAO.*(..))" />
<!-- 定义了将采用何种拦截操作这里引用到 txAdvice -->
<aop:advisor advice-ref="txAdvice"
pocut-ref="daoMethods" />
</aop:config>
<!-- 这是事务通知操作使用事务管理器引用自 transactionManager -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 指定哪些思路方法需要加入事务这里懒惰下全部加入可以使用通配符来只加入需要思路方法 -->
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
</beans>
其它加事务方式有老式Spring1.2, 还有Annotation, 这些都是个解决方案, 就是给DAO/Service加入事务. 如果您有更好办法, 欢迎来信探讨.
最新评论