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);
}
但是缺陷显而易见, 要有N多的代码要进行改动.
HibernateDaoSupport 代码里面的原始说明文档指出直接调用getSession()方法必须用配套的releaseSession(Session session)来释放连接, 根据我的测试, 就算配置了 OpenSessionInViewFilter(前提: 不加事务), 也不会关闭这个Session. 也许有人说可以用连接池, 这种情况和Db pool没关系, 用了pool就会发现连接很快就会满, 只会over的更快. 反过来, 如果不配置OpenSessionInViewFilter, 在DAO里提前用 releaseSession()关闭连接, 就可能会在JSP中出现Lazy载入异常. 另一个不配事务的问题就是无法更新或者插入数据.
不需要改原始代码的最终方案:
不过, 如果项目里已经有了大量直接调用getSession()而且没有加入事务配置的代码(如历史原因导致), 这些代码太多, 没法一一修改, 那就最好寻求其它方案, 最好是不需要修改原来的Java代码的方案. 我采用的这第三个方案是重写 HibernateDaoSupport用ThreadLocal保存Session列表并编写一个配套的过滤器来显式关闭Session, 并在关闭之前尝试提交事务. 下面是重写的 HibernateDaoSupport 代码:
package closesessionfiter;
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
*/
public abstract class HibernateDaoSupport extends DaoSupport {
/** 使用 ThreadLocal 保存打开的 Session 列表 */
private static final ThreadLocal<List<Session>> sessions = new ThreadLocal<List<Session>>();
/**
* 获取Hibernate连接.
*
* @return
*/
public static 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.
*/
public static void 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
*/
public final void 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) {
return new HibernateTemplate(sessionFactory);
}
/**
* Return the Hibernate SessionFactory used by this DAO.
*/
public final 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
*/
public final void 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.
*/
public final HibernateTemplate getHibernateTemplate() {
return this.hibernateTemplate;
}
protected final void checkDaoConfig() {
if (this.hibernateTemplate == null) {
throw new 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)
*/
protected final 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)
*/
protected final 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
*/
protected final DataAccessException convertHibernateAccessException(HibernateException ex) {
return this.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
*/
protected final void releaseSession(Session session) {
SessionFactoryUtils.releaseSession(session, getSessionFactory());
}
}
用这个类来覆盖Spring内置的那个HibernateDaoSupport, 然后随便编写一个过滤器, 如下所示:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* @author sutk.
* hibernate查询时,session不会自动关闭.
* 此过滤器用来关闭session.
*/
public class CloseSessionFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
chain.doFilter(req, res);
HibernateDaoSupport.closeSessionList();
}
public void init(FilterConfig arg0) throws ServletException {
}
}
把这个过滤器配置在过滤器链的第一个, 就OK了.
<!-- session关闭过滤器 -->
<filter>
<filter-name>sessionCloseFilter</filter-name>
<filter-class>
closesessionfiter.CloseSessionFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionCloseFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
最后也许会有人说, 为什么不用tx标签在Spring中来配置一个通配符就全部加入了事务了呢? 不过很遗憾, 经测试发现此方式无法实现跨DAO的Hibernate事务, 所以只好很无奈的放弃了这种方式.
配置事务管理:http://www.blogjava.net/robbie/archive/2009/04/05/264003.html