我正在尝试将Hibernate的使用升级到Hibernate 4。
我们有一堆Hibernate拦截器。这些使用了界面
public void beforeTransactionCompletion(Transaction tx)
接线完全正确,可在Hibernate3中使用。但是,通过对H4实用程序类的适当更改,它不会。
原因似乎是在调用接口之前数据库连接已关闭,因此我们得到了“连接已关闭”异常。
挖掘源代码,这似乎是因为在'triggerBeforeCompletion'的机制中,连接确实被关闭了。这似乎归结为 DataSourceUtils.beforeCompletion,它有以下注释:
// Release Connection early if the holder is not open anymore
// (that is, not used by another resource like a Hibernate Session
// that has its own cleanup via transaction synchronization),
// to avoid issues with strict JTA implementations that expect
// the close call before transaction completion.
在交易完成之前确保我的连接没有关闭的正确方法是什么?
@Bean
public Properties hibernatePropertiesLive()
{
Properties properties = new Properties();
properties.put("hibernate.dialect", dialect);
properties.put(Environment.SESSION_FACTORY_NAME, "LiveSession");
properties.put("hibernate.show_sql", "" + showSql);
properties.put("hibernate.format_sql", "" + formatSql);
properties.put("hibernate.jdbc.batch_size", "15");
properties.put("hibernate.generate_statistics", "true");
return properties;
}
@Bean
public LocalSessionFactoryBean SessionFactory() throws Exception {
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
bean.setMappingLocations(getResources());
bean.setHibernateProperties(hibernatePropertiesLive());
bean.setDataSource(dataSource);
bean.setCachingEnabled(false);
return bean;
}
@Bean
public HibernateTransactionManager TransactionManager()
{
HibernateTransactionManager theBean = new HibernateTransactionManager();
theBean.setSessionFactory(SessionFactory());
theBean.setEntityInterceptorBeanName("HibernateInterceptor");
theBean.setDefaultTimeout(300);
return theBean;
}
@Bean
@Scope("prototype")
public MyInterceptor HibernateInterceptor()
{
return new MyInterceptor();
}