好吧,这就是我实际所做的,我不知道这是否是这个问题的最佳解决方案,但在我们的情况下,由于我正在寻找最本地化的解决方案,这对我来说似乎是最好的。
我扩展了springframework.orm.hibernate3.HibernateTemplate,并创建了一个新的MyHibernateTemplate。新模板的主要作用是覆盖大多数休眠3的doExecute方法。HibernateTemplate最终导致并提供一些由旧的SessionFactoryUtils提供的功能(如isSessionTransactional和applicTransactionTimeout)。
新的doExecute复制了旧会话的逻辑,但不是SessionFactoryUtils.getNewSession来获取会话,而是首先尝试寻找一个开放的会话getSessionFactory().getCurrentSession() :
boolean newSessionOpened = false;
Session session;
if (enforceNewSession){
session = SessionFactoryUtils.openSession(getSessionFactory());
newSessionOpened = true;
} else {
try {
// look for an open session
session = getSessionFactory().getCurrentSession();
}
catch (HibernateException ex) {
try {
// if there isn't an open session, open one yourself
session = getSessionFactory().openSession();
newSessionOpened = true;
} catch (HibernateException e) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
}
// is the open session, is a session in a current transaction?
boolean existingTransaction = (!enforceNewSession &&
(!isAllowCreate() || isSessionTransactional(session, getSessionFactory())));
您只需要手动关闭此会话:
finally {
// if session was used in an existing transaction restore old settings
if (existingTransaction) {
//logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
}
// if not and a new session was opened close it
else {
// Never use deferred close for an explicitly new Session.
if (newSessionOpened) {
SessionFactoryUtils.closeSession(session);
//_log.info("Closing opened Hibernate session");
}
}
我试图保持这个答案简短,但如果有任何问题,我可以进一步阐述这个问题。