/**
  * Close the current transaction's EntityManager. Called after a transaction begin attempt failed.
  *
  * @param txObject the current transaction
  */
 protected void closeEntityManagerAfterFailedBegin(JpaTransactionObject txObject) {
   if (txObject.isNewEntityManagerHolder()) {
     EntityManager em = txObject.getEntityManagerHolder().getEntityManager();
     try {
       if (em.getTransaction().isActive()) {
         em.getTransaction().rollback();
       }
     } catch (Throwable ex) {
       logger.debug("Could not rollback EntityManager after failed transaction begin", ex);
     } finally {
       EntityManagerFactoryUtils.closeEntityManager(em);
     }
   }
 }
  @Override
  protected void doCleanupAfterCompletion(Object transaction) {
    JpaTransactionObject txObject = (JpaTransactionObject) transaction;

    // Remove the entity manager holder from the thread.
    if (txObject.isNewEntityManagerHolder()) {
      TransactionSynchronizationManager.unbindResource(getEntityManagerFactory());
    }
    txObject.getEntityManagerHolder().clear();

    // Remove the JDBC connection holder from the thread, if exposed.
    if (txObject.hasConnectionHolder()) {
      TransactionSynchronizationManager.unbindResource(getDataSource());
      try {
        getJpaDialect()
            .releaseJdbcConnection(
                txObject.getConnectionHolder().getConnectionHandle(),
                txObject.getEntityManagerHolder().getEntityManager());
      } catch (Exception ex) {
        // Just log it, to keep a transaction-related exception.
        logger.error("Could not close JDBC connection after transaction", ex);
      }
    }

    getJpaDialect().cleanupTransaction(txObject.getTransactionData());

    // Remove the entity manager holder from the thread.
    if (txObject.isNewEntityManagerHolder()) {
      EntityManager em = txObject.getEntityManagerHolder().getEntityManager();
      if (logger.isDebugEnabled()) {
        logger.debug("Closing JPA EntityManager [" + em + "] after transaction");
      }
      EntityManagerFactoryUtils.closeEntityManager(em);
    } else {
      logger.debug("Not closing pre-bound JPA EntityManager after transaction");
    }
  }