title: Spring, migration to hibernate4, Interceptors not working due to closed connections
body: <p>I am trying to upgrade our use of Hibernate to Hibernate 4.</p>
  
  <p>We have a bunch of Hibernate Interceptors. These make use of the interface</p>
  
  <pre><code>public void beforeTransactionCompletion(Transaction tx)
  </code></pre>
  
  <p>The wiring is all correct, and works in Hibernate3. However, with the appropriate changes to H4 utility classes, it does not.</p>
  
  <p>The reason for this seems to be that the database connection is closed <em>before</em> the interface is called, so we get a 'Connection is closed' exception.</p>
  
  <p>Digging through the source, this seems to be because in the mechanics of 'triggerBeforeCompletion', the connection is, indeed, being closed. This seems to boil down to
  DataSourceUtils.beforeCompletion, which has the following comment :</p>
  
  <pre><code>// 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.
  </code></pre>
  
  <p>What is the correct way to ensure that my connection is not closed before the transaction is completed?</p>
  
  <pre><code>@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();
  }
  </code></pre>