/*
   * Test method for
   * 'org.springframework.orm.jpa.EntityManagerFactoryUtils.doGetEntityManager(EntityManagerFactory)'
   */
  @Test
  public void testDoGetEntityManager() {
    // test null assertion
    try {
      EntityManagerFactoryUtils.doGetTransactionalEntityManager(null, null);
      fail("expected exception");
    } catch (IllegalArgumentException ex) {
      // it's okay
    }
    EntityManagerFactory factory = mock(EntityManagerFactory.class);

    // no tx active
    assertNull(EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
    assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
  }
 @Test
 public void testTranslatesIllegalArgumentException() {
   IllegalArgumentException iae = new IllegalArgumentException();
   DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(iae);
   assertSame(iae, dex.getCause());
   assertTrue(dex instanceof InvalidDataAccessApiUsageException);
 }
 /** We do not convert unknown exceptions. They may result from user code. */
 @Test
 public void testDoesNotTranslateUnfamiliarException() {
   UnsupportedOperationException userRuntimeException = new UnsupportedOperationException();
   assertNull(
       "Exception should not be wrapped",
       EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(userRuntimeException));
 }
 /**
  * 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);
     }
   }
 }
  @Test
  public void testDoGetEntityManagerWithTx() throws Exception {
    try {
      EntityManagerFactory factory = mock(EntityManagerFactory.class);
      EntityManager manager = mock(EntityManager.class);

      TransactionSynchronizationManager.initSynchronization();
      given(factory.createEntityManager()).willReturn(manager);

      // no tx active
      assertSame(manager, EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
      assertSame(
          manager,
          ((EntityManagerHolder) TransactionSynchronizationManager.unbindResource(factory))
              .getEntityManager());
    } finally {
      TransactionSynchronizationManager.clearSynchronization();
    }

    assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
  }
示例#6
0
  @Override
  public void load() {
    for (Map.Entry<String, DataSource> entry : domainsHolder.getDomains().entrySet()) {
      // create EntityManager so OpenJPA will build the SQL schema
      EntityManagerFactoryUtils.findEntityManagerFactory(
              ApplicationContextProvider.getBeanFactory(), entry.getKey())
          .createEntityManager();

      JdbcTemplate jdbcTemplate = new JdbcTemplate(entry.getValue());
      boolean existingData;
      try {
        existingData =
            jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + JPAConf.TABLE, Integer.class) > 0;
      } catch (DataAccessException e) {
        LOG.error("[{}] Could not access to table " + JPAConf.TABLE, entry.getKey(), e);
        existingData = true;
      }

      if (existingData) {
        LOG.info("[{}] Data found in the database, leaving untouched", entry.getKey());
      } else {
        LOG.info("[{}] Empty database found, loading default content", entry.getKey());

        try {
          ResourceWithFallbackLoader contentXML =
              ApplicationContextProvider.getBeanFactory()
                  .getBean(entry.getKey() + "ContentXML", ResourceWithFallbackLoader.class);
          loadDefaultContent(entry.getKey(), contentXML, entry.getValue());
        } catch (Exception e) {
          LOG.error("[{}] While loading default content", entry.getKey(), e);
        }
        try {
          createIndexes(entry.getKey(), entry.getValue());
          createViews(entry.getKey(), entry.getValue());
        } catch (IOException e) {
          LOG.error("[{}] While creating indexes and views", entry.getKey(), e);
        }
      }
    }
  }
  @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");
    }
  }
  /*
   * Test method for
   * 'org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessException(PersistenceException)'
   */
  @Test
  @SuppressWarnings("serial")
  public void testConvertJpaPersistenceException() {
    EntityNotFoundException entityNotFound = new EntityNotFoundException();
    assertSame(
        JpaObjectRetrievalFailureException.class,
        EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());

    NoResultException noResult = new NoResultException();
    assertSame(
        EmptyResultDataAccessException.class,
        EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());

    NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
    assertSame(
        IncorrectResultSizeDataAccessException.class,
        EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());

    OptimisticLockException optimisticLock = new OptimisticLockException();
    assertSame(
        JpaOptimisticLockingFailureException.class,
        EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());

    EntityExistsException entityExists = new EntityExistsException("foo");
    assertSame(
        DataIntegrityViolationException.class,
        EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());

    TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
    assertSame(
        InvalidDataAccessApiUsageException.class,
        EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired)
            .getClass());

    PersistenceException unknown = new PersistenceException() {};
    assertSame(
        JpaSystemException.class,
        EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
  }
 @Override
 protected void initEntityManager() {
   this.entityManager =
       EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory);
 }