Search in sources :

Example 86 with TransactionTemplate

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

the class JdbcTransactionManagerTests method testPropagationRequiresNewWithExistingTransactionAndUnrelatedDataSource.

@Test
public void testPropagationRequiresNewWithExistingTransactionAndUnrelatedDataSource() throws Exception {
    Connection con2 = mock(Connection.class);
    final DataSource ds2 = mock(DataSource.class);
    given(ds2.getConnection()).willReturn(con2);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    PlatformTransactionManager tm2 = new JdbcTransactionManager(ds2);
    final TransactionTemplate tt2 = new TransactionTemplate(tm2);
    tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    boolean condition4 = !TransactionSynchronizationManager.hasResource(ds);
    assertThat(condition4).as("Hasn't thread connection").isTrue();
    boolean condition3 = !TransactionSynchronizationManager.hasResource(ds2);
    assertThat(condition3).as("Hasn't thread connection").isTrue();
    boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
    assertThat(condition2).as("Synchronization not active").isTrue();
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            assertThat(status.isNewTransaction()).as("Is new transaction").isTrue();
            assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue();
            assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
            assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue();
            tt2.execute(new TransactionCallbackWithoutResult() {

                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                    assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue();
                    assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue();
                    assertThat(status.isNewTransaction()).as("Is new transaction").isTrue();
                    assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
                    assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue();
                    status.setRollbackOnly();
                }
            });
            assertThat(status.isNewTransaction()).as("Is new transaction").isTrue();
            assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
            assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue();
        }
    });
    boolean condition1 = !TransactionSynchronizationManager.hasResource(ds);
    assertThat(condition1).as("Hasn't thread connection").isTrue();
    boolean condition = !TransactionSynchronizationManager.hasResource(ds2);
    assertThat(condition).as("Hasn't thread connection").isTrue();
    verify(con).commit();
    verify(con).close();
    verify(con2).rollback();
    verify(con2).close();
}
Also used : Connection(java.sql.Connection) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) DataSource(javax.sql.DataSource) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 87 with TransactionTemplate

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

the class JdbcTransactionManagerTests method testTransactionWithPropagationNested.

@Test
public void testTransactionWithPropagationNested() throws Exception {
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
    boolean condition2 = !TransactionSynchronizationManager.hasResource(ds);
    assertThat(condition2).as("Hasn't thread connection").isTrue();
    boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive();
    assertThat(condition1).as("Synchronization not active").isTrue();
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            assertThat(status.isNewTransaction()).as("Is new transaction").isTrue();
        }
    });
    boolean condition = !TransactionSynchronizationManager.hasResource(ds);
    assertThat(condition).as("Hasn't thread connection").isTrue();
    verify(con).commit();
    verify(con).close();
}
Also used : TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 88 with TransactionTemplate

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

the class JdbcTransactionManagerTests method testParticipatingTransactionWithTransactionStartedFromSynch.

@Test
public void testParticipatingTransactionWithTransactionStartedFromSynch() throws Exception {
    boolean condition2 = !TransactionSynchronizationManager.hasResource(ds);
    assertThat(condition2).as("Hasn't thread connection").isTrue();
    boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive();
    assertThat(condition1).as("Synchronization not active").isTrue();
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    final TestTransactionSynchronization synch = new TestTransactionSynchronization(ds, TransactionSynchronization.STATUS_COMMITTED) {

        @Override
        protected void doAfterCompletion(int status) {
            super.doAfterCompletion(status);
            tt.execute(new TransactionCallbackWithoutResult() {

                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                }
            });
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            });
        }
    };
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            TransactionSynchronizationManager.registerSynchronization(synch);
        }
    });
    boolean condition = !TransactionSynchronizationManager.hasResource(ds);
    assertThat(condition).as("Hasn't thread connection").isTrue();
    assertThat(synch.beforeCommitCalled).isTrue();
    assertThat(synch.beforeCompletionCalled).isTrue();
    assertThat(synch.afterCommitCalled).isTrue();
    assertThat(synch.afterCompletionCalled).isTrue();
    boolean condition3 = synch.afterCompletionException instanceof IllegalStateException;
    assertThat(condition3).isTrue();
    verify(con, times(2)).commit();
    verify(con, times(2)).close();
}
Also used : Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) TransactionSynchronization(org.springframework.transaction.support.TransactionSynchronization) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 89 with TransactionTemplate

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

the class JdbcTransactionManagerTests method transactionWithTimeout.

@ParameterizedTest(name = "transaction with {0} second timeout")
@ValueSource(ints = { 1, 10 })
@EnabledForTestGroups(LONG_RUNNING)
public void transactionWithTimeout(int timeout) throws Exception {
    PreparedStatement ps = mock(PreparedStatement.class);
    given(con.getAutoCommit()).willReturn(true);
    given(con.prepareStatement("some SQL statement")).willReturn(ps);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setTimeout(timeout);
    boolean condition1 = !TransactionSynchronizationManager.hasResource(ds);
    assertThat(condition1).as("Hasn't thread connection").isTrue();
    try {
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException ex) {
                }
                try {
                    Connection con = DataSourceUtils.getConnection(ds);
                    PreparedStatement ps = con.prepareStatement("some SQL statement");
                    DataSourceUtils.applyTransactionTimeout(ps, ds);
                } catch (SQLException ex) {
                    throw new DataAccessResourceFailureException("", ex);
                }
            }
        });
        if (timeout <= 1) {
            fail("Should have thrown TransactionTimedOutException");
        }
    } catch (TransactionTimedOutException ex) {
        if (timeout <= 1) {
        // expected
        } else {
            throw ex;
        }
    }
    boolean condition = !TransactionSynchronizationManager.hasResource(ds);
    assertThat(condition).as("Hasn't thread connection").isTrue();
    if (timeout > 1) {
        verify(ps).setQueryTimeout(timeout - 1);
        verify(con).commit();
    } else {
        verify(con).rollback();
    }
    InOrder ordered = inOrder(con);
    ordered.verify(con).setAutoCommit(false);
    ordered.verify(con).setAutoCommit(true);
    verify(con).close();
}
Also used : TransactionTimedOutException(org.springframework.transaction.TransactionTimedOutException) InOrder(org.mockito.InOrder) UncategorizedSQLException(org.springframework.jdbc.UncategorizedSQLException) SQLException(java.sql.SQLException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Connection(java.sql.Connection) TransactionStatus(org.springframework.transaction.TransactionStatus) PreparedStatement(java.sql.PreparedStatement) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) EnabledForTestGroups(org.springframework.core.testfixture.EnabledForTestGroups)

Example 90 with TransactionTemplate

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

the class JdbcTransactionManagerTests method testTransactionWithDataAccessExceptionOnRollback.

@Test
public void testTransactionWithDataAccessExceptionOnRollback() throws Exception {
    given(con.getAutoCommit()).willReturn(true);
    willThrow(new SQLException("Cannot rollback")).given(con).rollback();
    tm.setExceptionTranslator((task, sql, ex) -> new ConcurrencyFailureException(task));
    TransactionTemplate tt = new TransactionTemplate(tm);
    assertThatExceptionOfType(ConcurrencyFailureException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            status.setRollbackOnly();
        }
    }));
    boolean condition = !TransactionSynchronizationManager.hasResource(ds);
    assertThat(condition).as("Hasn't thread connection").isTrue();
    InOrder ordered = inOrder(con);
    ordered.verify(con).setAutoCommit(false);
    ordered.verify(con).rollback();
    ordered.verify(con).setAutoCommit(true);
    verify(con).close();
}
Also used : InOrder(org.mockito.InOrder) UncategorizedSQLException(org.springframework.jdbc.UncategorizedSQLException) SQLException(java.sql.SQLException) ConcurrencyFailureException(org.springframework.dao.ConcurrencyFailureException) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

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