2

我正在尝试将我们对 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();
}
4

0 回答 0