Ido*_*.Co 21 java spring hibernate
我正在将我们的项目从Hibernate 3.0升级到Hibernate 4.1.6.(我们目前正在使用弹簧3.1)
我在很多文章和HibernateTemplate文档中都读过,因为版本4.0不支持HibernateTemplate,我应该用调用sessionFactory.getCurrentSession()来取代会话来替换它的用法.
由于这个项目是在较早版本的Hibernate中启动的,HibernateTemplate因此鼓励使用它,我们目前在HibernateTemplate整个项目中有124个用法.我担心替换所有这些事件sessionFactory.getCurrentSession()可能会在我们的项目中插入回归错误.此外,还有一些地方HibernateTemplate用于非交易环境,没有"当前"会话.在这些情况下我该怎么办?打开一个新会话并自己处理(关闭)它?我使用时并非如此HibernateTemplate.
你有解决这些问题的好策略吗?
谢谢.
相关阅读:
Ido*_*.Co 11
好的,所以这就是我实际做的,我不知道这是否是解决这个问题的最佳解决方案,但在我们的情况下,由于我在寻找最本地化的解决方案,对我来说似乎是最好的.
我扩展了springframework.orm.hibernate3.HibernateTemplate并创建了一个新的MyHibernateTemplate.新模板的主要作用是覆盖大多数hibernate3.HibernateTemplate最终导致的doExecute方法,并提供旧的SessionFactoryUtils提供的一些功能(如isSessionTransactional和applyTransactionTimeout).
新的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())));
Run Code Online (Sandbox Code Playgroud)
您只需手动关闭此会话:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
我试着保持这个答案简短,但如果有任何问题我可以进一步详细说明这个问题.
| 归档时间: |
|
| 查看次数: |
10308 次 |
| 最近记录: |