title: Can't join JDBC transaction with JTA transaction with Hibernate 4/Hibernate 5 on Glassfish 4 when flush() is manually called
body: <p>I'm trying to move our application forward. Now it runs under Glassfish 3, JAVA EE 6 and uses Hibernate 3 as the JPA implementation.
  I wrote an example that shows a problem I've with transactions. In some circumnstances the application needs to manually call the entity manager flush() method. But even in a JTA environment, what happens is that the flush() causes a physical commit on the underlying database (we're using ojdbc6.jar JDBC driver to connect to ORACLE X/XI). This is not the expected behaviour, due to the fact that the JDBC transaction should join the JTA transaction. If after the flush() an exception is raised by the EJB, the data flushed should be rollbacked.
  In Hibernate 3 everything works perfectly. In  Hibernate 4.3.5 it doesn't. </p>
  
  <p>Debugging the Hibernate 4.3 code I found this</p>
  
  <pre><code>package org.hibernate.jpa.internal.EntityManagerImpl
  
             @Override
             protected Session internalGetSession() {
                            if ( session == null ) {
                                          ...
                                          SessionBuilderImplementor sessionBuilder = internalGetEntityManagerFactory().getSessionFactory().withOptions();
  
  ---&gt;&gt;&gt;&gt;&gt;&gt;          sessionBuilder.autoJoinTransactions( getTransactionType() != PersistenceUnitTransactionType.JTA ); &lt;&lt;&lt;&lt;&lt;&lt;-----
  
                                          session = sessionBuilder.openSession();
                            }
                            return session;
             }
  </code></pre>
  
  <p>This leads the org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl.attemptToRegisterJtaSync() method to entering in this block and skipping the synchronization with the JTA platform..</p>
  
  <pre><code> ....
             final JoinStatus joinStatus = currentHibernateTransaction.getJoinStatus();
             if ( joinStatus != JoinStatus.JOINED ) {
                                          // the transaction is not (yet) joined, see if we should join...
   ----&gt;&gt;&gt;&gt;&gt;            if ( !transactionContext.shouldAutoJoinTransaction() ) {  &lt;&lt;&lt;&lt;&lt;&lt;----
                                                         // we are supposed to not auto join transactions; if the transaction is not marked for join
                                                         // we cannot go any further in attempting to join (register sync).
                                                         if ( joinStatus != JoinStatus.MARKED_FOR_JOINED ) {
                                                                        if (isDebugging) {
                                                                                       LOG.debug( "Skipping JTA sync registration due to auto join checking" );
                                                                        }
                                                                        return;
                                                         }
                                          }
                            }
  </code></pre>
  
  <p>I tried to debug Hibernate 5 and here the AutoJoinTransaction problem disappeared, most of the transaction code has been rewritten. In any case, the flush() problem is still present. </p>
  
  <p>I wrote a small example that demonstrates it. </p>
  
  <pre><code>@Stateless
  public class BaseServicesAdapterImpl implements BaseServicesAdapterInterface {
  
      @PersistenceContext 
      protected EntityManager em;
  
      @Resource SessionContext sessionContext;
  
      public EntityManager getEm() {
          return em;
      }
  
      public void setEm(EntityManager em) {
          this.em = em;
      }
  
      @Override
      public String test() {
          persistEntityAndFlush();
          return "finished";
      }
  
  
      private void persistEntityAndFlush() {
          persistEntityAndFlush("TST", new Integer(5), new Long(-1), new Long(-1), 
                  new Date(), "", null, new Date(), new Integer(10), "test transaction", 
                  null, null, null, "");      
      }
  
  
      private Long persistEntityAndFlush(String tipoProcesso, Integer tpEntita, Long idEntita, Long progr,
              Date date, String stato, String subStato, Date dtStato, Integer ggTimer,
              String descrizione, String idPrcPerif1, String idPrcPerif2, String idPrcPerif3, String chiave1) {
              Long idProcesso = 0L;
  
              TestEntity testEntity = new TestEntity();
              testEntity.setTpEntita(tpEntita);
              testEntity.setIdEntita(idEntita);
              testEntity.setIdProcesso(idProcesso);
  
              //.....
  
              getEm().persist(testEntity);
  
              //***** THIS FLUSH COMMITS THE DATA *****
              getEm().flush(); 
  
              throw new RuntimeException("Too late?");
      }
  
  
  }
  </code></pre>
  
  <p>This is the perstistence.xml file</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;persistence xmlns="http://java.sun.com/xml/ns/persistence"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
      version="1.0"&gt;
  
      &lt;persistence-unit name="test_pu" transaction-type="JTA"&gt;
          &lt;provider&gt;org.hibernate.jpa.HibernatePersistenceProvider&lt;/provider&gt;
          &lt;jta-data-source&gt;dsName&lt;/jta-data-source&gt;
          &lt;properties&gt;
              &lt;property name="hibernate.hbm2ddl.auto" value="none" /&gt;
              &lt;property name="hibernate.show_sql" value="true" /&gt;
              &lt;property name="hibernate.format_sql" value="false" /&gt;
              &lt;property name="hibernate.use_sql_comments" value="false" /&gt;
              &lt;property name="hibernate.generate_statistics" value="false" /&gt;
              &lt;property name="hibernate.ejb.metamodel.generation" value="disabled" /&gt;
  
              &lt;!-- removing this does not affect anything --&gt;
              &lt;property name="hibernate.connection.release_mode" value="after_transaction" /&gt;
  
              &lt;property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" /&gt;
              &lt;property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" /&gt;            
          &lt;/properties&gt;
      &lt;/persistence-unit&gt;
  &lt;/persistence&gt;
  </code></pre>
  
  <p>What am I missing?
  Any help will be appreciated.
  Thanks in advance,</p>
  
  <p>David Obber</p>