Search in sources :

Example 96 with TransactionTemplate

use of org.springframework.transaction.support.TransactionTemplate in project spring-framework by spring-projects.

the class JpaTransactionManagerTests method testPropagationSupportsAndRequiresNew.

@Test
public void testPropagationSupportsAndRequiresNew() {
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    given(manager.getTransaction()).willReturn(tx);
    final List<String> l = new ArrayList<>();
    l.add("test");
    boolean condition3 = !TransactionSynchronizationManager.hasResource(factory);
    assertThat(condition3).isTrue();
    boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
    assertThat(condition2).isTrue();
    Object result = tt.execute(status -> {
        assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
        TransactionTemplate tt2 = new TransactionTemplate(tm);
        tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        return tt2.execute(status1 -> {
            EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
            return l;
        });
    });
    assertThat(result).isSameAs(l);
    boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
    assertThat(condition1).isTrue();
    boolean condition = !TransactionSynchronizationManager.isSynchronizationActive();
    assertThat(condition).isTrue();
    verify(tx).commit();
    verify(manager).flush();
    verify(manager).close();
}
Also used : ArrayList(java.util.ArrayList) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Test(org.junit.jupiter.api.Test)

Example 97 with TransactionTemplate

use of org.springframework.transaction.support.TransactionTemplate in project spring-framework by spring-projects.

the class JpaTransactionManagerTests method setup.

@BeforeEach
public void setup() {
    factory = mock(EntityManagerFactory.class);
    manager = mock(EntityManager.class);
    tx = mock(EntityTransaction.class);
    tm = new JpaTransactionManager(factory);
    tt = new TransactionTemplate(tm);
    given(factory.createEntityManager()).willReturn(manager);
    given(manager.getTransaction()).willReturn(tx);
    given(manager.isOpen()).willReturn(true);
}
Also used : EntityTransaction(jakarta.persistence.EntityTransaction) EntityManager(jakarta.persistence.EntityManager) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 98 with TransactionTemplate

use of org.springframework.transaction.support.TransactionTemplate in project spring-framework by spring-projects.

the class SqlScriptsTestExecutionListener method executeSqlScripts.

/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link 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, 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(new Resource[0]));
    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() == 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, 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(org.springframework.transaction.interceptor.TransactionAttribute) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) ResourceDatabasePopulator(org.springframework.jdbc.datasource.init.ResourceDatabasePopulator) ClassPathResource(org.springframework.core.io.ClassPathResource) ByteArrayResource(org.springframework.core.io.ByteArrayResource) Resource(org.springframework.core.io.Resource) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) ByteArrayResource(org.springframework.core.io.ByteArrayResource) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) DataSource(javax.sql.DataSource)

Example 99 with TransactionTemplate

use of org.springframework.transaction.support.TransactionTemplate in project spring-framework by spring-projects.

the class JtaTransactionManagerTests method jtaTransactionManagerWithUnsupportedOperationExceptionOnNestedBegin.

@Test
public void jtaTransactionManagerWithUnsupportedOperationExceptionOnNestedBegin() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
    willThrow(new UnsupportedOperationException("not supported")).given(ut).begin();
    assertThatExceptionOfType(NestedTransactionNotSupportedException.class).isThrownBy(() -> {
        JtaTransactionManager ptm = newJtaTransactionManager(ut);
        TransactionTemplate tt = new TransactionTemplate(ptm);
        tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
            // something transactional
            }
        });
    });
}
Also used : UserTransaction(jakarta.transaction.UserTransaction) JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.jupiter.api.Test)

Example 100 with TransactionTemplate

use of org.springframework.transaction.support.TransactionTemplate in project spring-framework by spring-projects.

the class JtaTransactionManagerTests method jtaTransactionManagerWithPropagationRequiresNewAndExistingWithBeginException.

@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndExistingWithBeginException() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    TransactionManager tm = mock(TransactionManager.class);
    Transaction tx = mock(Transaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
    given(tm.suspend()).willReturn(tx);
    willThrow(new SystemException()).given(ut).begin();
    JtaTransactionManager ptm = newJtaTransactionManager(ut, tm);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
    assertThatExceptionOfType(CannotCreateTransactionException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
        }
    }));
    assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
    verify(tm).resume(tx);
}
Also used : UserTransaction(jakarta.transaction.UserTransaction) JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) Transaction(jakarta.transaction.Transaction) UserTransaction(jakarta.transaction.UserTransaction) SystemException(jakarta.transaction.SystemException) TransactionManager(jakarta.transaction.TransactionManager) JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.jupiter.api.Test)

Aggregations

TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)287 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)178 TransactionStatus (org.springframework.transaction.TransactionStatus)158 Test (org.junit.jupiter.api.Test)139 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)70 JtaTransactionManager (org.springframework.transaction.jta.JtaTransactionManager)56 UserTransaction (jakarta.transaction.UserTransaction)43 SQLException (java.sql.SQLException)36 UncategorizedSQLException (org.springframework.jdbc.UncategorizedSQLException)29 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)25 Connection (java.sql.Connection)23 Test (org.junit.Test)22 TransactionSynchronization (org.springframework.transaction.support.TransactionSynchronization)22 InOrder (org.mockito.InOrder)21 UnexpectedRollbackException (org.springframework.transaction.UnexpectedRollbackException)18 PlatformTransactionManager (org.springframework.transaction.PlatformTransactionManager)17 DataSource (javax.sql.DataSource)16 DatabaseMetaData (java.sql.DatabaseMetaData)12 PreparedStatement (java.sql.PreparedStatement)12 Savepoint (java.sql.Savepoint)12