Search in sources :

Example 1 with DefaultTransactionAttribute

use of cn.taketoday.transaction.interceptor.DefaultTransactionAttribute in project today-infrastructure by TAKETODAY.

the class LocalContainerEntityManagerFactoryBeanTests method testApplicationManagedEntityManagerWithJtaTransaction.

@Test
public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception {
    Object testEntity = new Object();
    // This one's for the tx (shared)
    EntityManager sharedEm = mock(EntityManager.class);
    given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
    // This is the application-specific one
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo());
    pui.setTransactionType(PersistenceUnitTransactionType.JTA);
    JpaTransactionManager jpatm = new JpaTransactionManager();
    jpatm.setEntityManagerFactory(cefb.getObject());
    TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
    EntityManagerFactory emf = cefb.getObject();
    assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf);
    assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertThat(em.contains(testEntity)).isFalse();
    jpatm.commit(txStatus);
    cefb.destroy();
    verify(mockEm).joinTransaction();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
Also used : EntityManager(jakarta.persistence.EntityManager) DefaultTransactionAttribute(cn.taketoday.transaction.interceptor.DefaultTransactionAttribute) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) TransactionStatus(cn.taketoday.transaction.TransactionStatus) MutablePersistenceUnitInfo(cn.taketoday.orm.jpa.persistenceunit.MutablePersistenceUnitInfo) Test(org.junit.jupiter.api.Test)

Example 2 with DefaultTransactionAttribute

use of cn.taketoday.transaction.interceptor.DefaultTransactionAttribute in project today-infrastructure by TAKETODAY.

the class LocalContainerEntityManagerFactoryBeanTests method testApplicationManagedEntityManagerWithTransaction.

@Test
public void testApplicationManagedEntityManagerWithTransaction() throws Exception {
    Object testEntity = new Object();
    EntityTransaction mockTx = mock(EntityTransaction.class);
    // This one's for the tx (shared)
    EntityManager sharedEm = mock(EntityManager.class);
    given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
    // This is the application-specific one
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEm.getTransaction()).willReturn(mockTx);
    given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    JpaTransactionManager jpatm = new JpaTransactionManager();
    jpatm.setEntityManagerFactory(cefb.getObject());
    TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
    EntityManagerFactory emf = cefb.getObject();
    assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf);
    assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertThat(em.contains(testEntity)).isFalse();
    jpatm.commit(txStatus);
    cefb.destroy();
    verify(mockTx).begin();
    verify(mockTx).commit();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
Also used : EntityTransaction(jakarta.persistence.EntityTransaction) EntityManager(jakarta.persistence.EntityManager) DefaultTransactionAttribute(cn.taketoday.transaction.interceptor.DefaultTransactionAttribute) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) TransactionStatus(cn.taketoday.transaction.TransactionStatus) Test(org.junit.jupiter.api.Test)

Example 3 with DefaultTransactionAttribute

use of cn.taketoday.transaction.interceptor.DefaultTransactionAttribute in project today-infrastructure by TAKETODAY.

the class LocalContainerEntityManagerFactoryBeanTests method testApplicationManagedEntityManagerWithTransactionAndCommitException.

@Test
public void testApplicationManagedEntityManagerWithTransactionAndCommitException() throws Exception {
    Object testEntity = new Object();
    EntityTransaction mockTx = mock(EntityTransaction.class);
    willThrow(new OptimisticLockException()).given(mockTx).commit();
    // This one's for the tx (shared)
    EntityManager sharedEm = mock(EntityManager.class);
    given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
    // This is the application-specific one
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEm.getTransaction()).willReturn(mockTx);
    given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    JpaTransactionManager jpatm = new JpaTransactionManager();
    jpatm.setEntityManagerFactory(cefb.getObject());
    TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
    EntityManagerFactory emf = cefb.getObject();
    assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf);
    assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertThat(em.contains(testEntity)).isFalse();
    assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> jpatm.commit(txStatus));
    cefb.destroy();
    verify(mockTx).begin();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
Also used : EntityTransaction(jakarta.persistence.EntityTransaction) EntityManager(jakarta.persistence.EntityManager) OptimisticLockingFailureException(cn.taketoday.dao.OptimisticLockingFailureException) DefaultTransactionAttribute(cn.taketoday.transaction.interceptor.DefaultTransactionAttribute) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) OptimisticLockException(jakarta.persistence.OptimisticLockException) TransactionStatus(cn.taketoday.transaction.TransactionStatus) Test(org.junit.jupiter.api.Test)

Example 4 with DefaultTransactionAttribute

use of cn.taketoday.transaction.interceptor.DefaultTransactionAttribute in project today-infrastructure by TAKETODAY.

the class SqlScriptsTestExecutionListener method executeSqlScripts.

/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link Sql.ExecutionPhase} and {@link TestContext}.
 * <p>Special care must be taken in order to properly support the configured
 * {@link SqlConfig#transactionMode}.
 *
 * @param sql the {@code @Sql} annotation to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
 */
private void executeSqlScripts(Sql sql, Sql.ExecutionPhase executionPhase, TestContext testContext, boolean classLevel) {
    if (executionPhase != sql.executionPhase()) {
        return;
    }
    MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.", mergedSqlConfig, executionPhase, testContext));
    }
    String[] scripts = getScripts(sql, testContext, classLevel);
    scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
    List<Resource> scriptResources = TestContextResourceUtils.convertToResourceList(testContext.getApplicationContext(), scripts);
    for (String stmt : sql.statements()) {
        if (StringUtils.hasText(stmt)) {
            stmt = stmt.trim();
            scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
        }
    }
    ResourceDatabasePopulator populator = createDatabasePopulator(mergedSqlConfig);
    populator.setScripts(scriptResources.toArray(Resource.EMPTY_ARRAY));
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
    }
    String dsName = mergedSqlConfig.getDataSource();
    String tmName = mergedSqlConfig.getTransactionManager();
    DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
    PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext, tmName);
    boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == SqlConfig.TransactionMode.ISOLATED);
    if (txMgr == null) {
        Assert.state(!newTxRequired, () -> String.format("Failed to execute SQL scripts for test context %s: " + "cannot execute SQL scripts using Transaction Mode " + "[%s] without a PlatformTransactionManager.", testContext, SqlConfig.TransactionMode.ISOLATED));
        Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for test context %s: " + "supply at least a DataSource or PlatformTransactionManager.", testContext));
        // Execute scripts directly against the DataSource
        populator.execute(dataSource);
    } else {
        DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
        // Ensure user configured an appropriate DataSource/TransactionManager pair.
        if (dataSource != null && dataSourceFromTxMgr != null && !sameDataSource(dataSource, dataSourceFromTxMgr)) {
            throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: " + "the configured DataSource [%s] (named '%s') is not the one associated with " + "transaction manager [%s] (named '%s').", testContext, dataSource.getClass().getName(), dsName, txMgr.getClass().getName(), tmName));
        }
        if (dataSource == null) {
            dataSource = dataSourceFromTxMgr;
            Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for " + "test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').", testContext, txMgr.getClass().getName(), tmName));
        }
        final DataSource finalDataSource = dataSource;
        int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW : TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(testContext, new DefaultTransactionAttribute(propagation));
        new TransactionTemplate(txMgr, txAttr).executeWithoutResult(s -> populator.execute(finalDataSource));
    }
}
Also used : TransactionAttribute(cn.taketoday.transaction.interceptor.TransactionAttribute) DefaultTransactionAttribute(cn.taketoday.transaction.interceptor.DefaultTransactionAttribute) DefaultTransactionAttribute(cn.taketoday.transaction.interceptor.DefaultTransactionAttribute) ResourceDatabasePopulator(cn.taketoday.jdbc.datasource.init.ResourceDatabasePopulator) Resource(cn.taketoday.core.io.Resource) ClassPathResource(cn.taketoday.core.io.ClassPathResource) ByteArrayResource(cn.taketoday.core.io.ByteArrayResource) TransactionTemplate(cn.taketoday.transaction.support.TransactionTemplate) ByteArrayResource(cn.taketoday.core.io.ByteArrayResource) PlatformTransactionManager(cn.taketoday.transaction.PlatformTransactionManager) DataSource(javax.sql.DataSource)

Example 5 with DefaultTransactionAttribute

use of cn.taketoday.transaction.interceptor.DefaultTransactionAttribute in project today-framework by TAKETODAY.

the class LocalContainerEntityManagerFactoryBeanTests method testApplicationManagedEntityManagerWithTransaction.

@Test
public void testApplicationManagedEntityManagerWithTransaction() throws Exception {
    Object testEntity = new Object();
    EntityTransaction mockTx = mock(EntityTransaction.class);
    // This one's for the tx (shared)
    EntityManager sharedEm = mock(EntityManager.class);
    given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
    // This is the application-specific one
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEm.getTransaction()).willReturn(mockTx);
    given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    JpaTransactionManager jpatm = new JpaTransactionManager();
    jpatm.setEntityManagerFactory(cefb.getObject());
    TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
    EntityManagerFactory emf = cefb.getObject();
    assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf);
    assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertThat(em.contains(testEntity)).isFalse();
    jpatm.commit(txStatus);
    cefb.destroy();
    verify(mockTx).begin();
    verify(mockTx).commit();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
Also used : EntityTransaction(jakarta.persistence.EntityTransaction) EntityManager(jakarta.persistence.EntityManager) DefaultTransactionAttribute(cn.taketoday.transaction.interceptor.DefaultTransactionAttribute) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) TransactionStatus(cn.taketoday.transaction.TransactionStatus) Test(org.junit.jupiter.api.Test)

Aggregations

DefaultTransactionAttribute (cn.taketoday.transaction.interceptor.DefaultTransactionAttribute)8 TransactionStatus (cn.taketoday.transaction.TransactionStatus)6 EntityManager (jakarta.persistence.EntityManager)6 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)6 Test (org.junit.jupiter.api.Test)6 EntityTransaction (jakarta.persistence.EntityTransaction)4 ByteArrayResource (cn.taketoday.core.io.ByteArrayResource)2 ClassPathResource (cn.taketoday.core.io.ClassPathResource)2 Resource (cn.taketoday.core.io.Resource)2 OptimisticLockingFailureException (cn.taketoday.dao.OptimisticLockingFailureException)2 ResourceDatabasePopulator (cn.taketoday.jdbc.datasource.init.ResourceDatabasePopulator)2 MutablePersistenceUnitInfo (cn.taketoday.orm.jpa.persistenceunit.MutablePersistenceUnitInfo)2 PlatformTransactionManager (cn.taketoday.transaction.PlatformTransactionManager)2 TransactionAttribute (cn.taketoday.transaction.interceptor.TransactionAttribute)2 TransactionTemplate (cn.taketoday.transaction.support.TransactionTemplate)2 OptimisticLockException (jakarta.persistence.OptimisticLockException)2 DataSource (javax.sql.DataSource)2