Search in sources :

Example 11 with TransactionTemplate

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

the class DataSourceTransactionManagerTests method testTransactionWithEnforceReadOnly.

@Test
public void testTransactionWithEnforceReadOnly() throws Exception {
    tm.setEnforceReadOnly(true);
    given(con.getAutoCommit()).willReturn(true);
    Statement stmt = mock(Statement.class);
    given(con.createStatement()).willReturn(stmt);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    tt.setReadOnly(true);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
        // something transactional
        }
    });
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    InOrder ordered = inOrder(con, stmt);
    ordered.verify(con).setAutoCommit(false);
    ordered.verify(stmt).executeUpdate("SET TRANSACTION READ ONLY");
    ordered.verify(stmt).close();
    ordered.verify(con).commit();
    ordered.verify(con).setAutoCommit(true);
    ordered.verify(con).close();
}
Also used : InOrder(org.mockito.InOrder) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.Test)

Example 12 with TransactionTemplate

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

the class DataSourceTransactionManagerTests method testTransactionAwareDataSourceProxyWithSuspensionAndReobtaining.

@Test
public void testTransactionAwareDataSourceProxyWithSuspensionAndReobtaining() throws Exception {
    given(con.getAutoCommit()).willReturn(true);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            // something transactional
            assertEquals(con, DataSourceUtils.getConnection(ds));
            final TransactionAwareDataSourceProxy dsProxy = new TransactionAwareDataSourceProxy(ds);
            dsProxy.setReobtainTransactionalConnections(true);
            try {
                assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection());
                // should be ignored
                dsProxy.getConnection().close();
            } catch (SQLException ex) {
                throw new UncategorizedSQLException("", "", ex);
            }
            tt.execute(new TransactionCallbackWithoutResult() {

                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    // something transactional
                    assertEquals(con, DataSourceUtils.getConnection(ds));
                    try {
                        assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection());
                        // should be ignored
                        dsProxy.getConnection().close();
                    } catch (SQLException ex) {
                        throw new UncategorizedSQLException("", "", ex);
                    }
                }
            });
            try {
                assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection());
                // should be ignored
                dsProxy.getConnection().close();
            } catch (SQLException ex) {
                throw new UncategorizedSQLException("", "", ex);
            }
        }
    });
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    InOrder ordered = inOrder(con);
    ordered.verify(con).setAutoCommit(false);
    ordered.verify(con).commit();
    ordered.verify(con).setAutoCommit(true);
    verify(con, times(2)).close();
}
Also used : UncategorizedSQLException(org.springframework.jdbc.UncategorizedSQLException) InOrder(org.mockito.InOrder) UncategorizedSQLException(org.springframework.jdbc.UncategorizedSQLException) SQLException(java.sql.SQLException) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.Test)

Example 13 with TransactionTemplate

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

the class DataSourceTransactionManagerTests method doTestExistingTransactionWithPropagationNested.

private void doTestExistingTransactionWithPropagationNested(final int count) throws Exception {
    DatabaseMetaData md = mock(DatabaseMetaData.class);
    Savepoint sp = mock(Savepoint.class);
    given(md.supportsSavepoints()).willReturn(true);
    given(con.getMetaData()).willReturn(md);
    for (int i = 1; i <= count; i++) {
        given(con.setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + i)).willReturn(sp);
    }
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            assertTrue("Is new transaction", status.isNewTransaction());
            assertTrue("Isn't nested transaction", !status.hasSavepoint());
            for (int i = 0; i < count; i++) {
                tt.execute(new TransactionCallbackWithoutResult() {

                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                        assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
                        assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive());
                        assertTrue("Isn't new transaction", !status.isNewTransaction());
                        assertTrue("Is nested transaction", status.hasSavepoint());
                    }
                });
            }
            assertTrue("Is new transaction", status.isNewTransaction());
            assertTrue("Isn't nested transaction", !status.hasSavepoint());
        }
    });
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    verify(con, times(count)).releaseSavepoint(sp);
    verify(con).commit();
    verify(con).close();
}
Also used : TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) Savepoint(java.sql.Savepoint) DatabaseMetaData(java.sql.DatabaseMetaData) Savepoint(java.sql.Savepoint) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult)

Example 14 with TransactionTemplate

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

the class DataSourceJtaTransactionTests method testJtaTransactionWithConnectionHolderStillBound.

@Test
public void testJtaTransactionWithConnectionHolderStillBound() throws Exception {
    @SuppressWarnings("serial") JtaTransactionManager ptm = new JtaTransactionManager(userTransaction) {

        @Override
        protected void doRegisterAfterCompletionWithJtaTransaction(JtaTransactionObject txObject, final List<TransactionSynchronization> synchronizations) throws RollbackException, SystemException {
            Thread async = new Thread() {

                @Override
                public void run() {
                    invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_COMMITTED);
                }
            };
            async.start();
            try {
                async.join();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    };
    TransactionTemplate tt = new TransactionTemplate(ptm);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
    given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE);
    for (int i = 0; i < 3; i++) {
        final boolean releaseCon = (i != 1);
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
                assertTrue("Is existing transaction", !status.isNewTransaction());
                Connection c = DataSourceUtils.getConnection(dataSource);
                assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
                DataSourceUtils.releaseConnection(c, dataSource);
                c = DataSourceUtils.getConnection(dataSource);
                assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
                if (releaseCon) {
                    DataSourceUtils.releaseConnection(c, dataSource);
                }
            }
        });
        if (!releaseCon) {
            assertTrue("Still has connection holder", TransactionSynchronizationManager.hasResource(dataSource));
        } else {
            assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
        }
        assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
    }
    verify(connection, times(3)).close();
}
Also used : TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Connection(java.sql.Connection) JtaTransactionObject(org.springframework.transaction.jta.JtaTransactionObject) TransactionStatus(org.springframework.transaction.TransactionStatus) JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) List(java.util.List) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.Test)

Example 15 with TransactionTemplate

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

the class DataSourceJtaTransactionTests method doTestJtaTransactionWithPropagationRequiresNewAndBeginException.

private void doTestJtaTransactionWithPropagationRequiresNewAndBeginException(boolean suspendException, final boolean openOuterConnection, final boolean useTransactionAwareDataSource) throws Exception {
    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
    if (suspendException) {
        given(transactionManager.suspend()).willThrow(new SystemException());
    } else {
        given(transactionManager.suspend()).willReturn(transaction);
        willThrow(new SystemException()).given(userTransaction).begin();
    }
    given(connection.isReadOnly()).willReturn(true);
    final DataSource dsToUse = useTransactionAwareDataSource ? new TransactionAwareDataSourceProxy(dataSource) : dataSource;
    if (dsToUse instanceof TransactionAwareDataSourceProxy) {
        ((TransactionAwareDataSourceProxy) dsToUse).setReobtainTransactionalConnections(true);
    }
    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    final TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
    try {
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
                assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
                assertTrue("Is new transaction", status.isNewTransaction());
                Connection c = DataSourceUtils.getConnection(dsToUse);
                try {
                    assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
                    c.isReadOnly();
                    DataSourceUtils.releaseConnection(c, dsToUse);
                    c = DataSourceUtils.getConnection(dsToUse);
                    assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
                    if (!openOuterConnection) {
                        DataSourceUtils.releaseConnection(c, dsToUse);
                    }
                } catch (SQLException ex) {
                }
                try {
                    tt.execute(new TransactionCallbackWithoutResult() {

                        @Override
                        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                            assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
                            assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
                            assertTrue("Is new transaction", status.isNewTransaction());
                            Connection c = DataSourceUtils.getConnection(dsToUse);
                            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
                            DataSourceUtils.releaseConnection(c, dsToUse);
                            c = DataSourceUtils.getConnection(dsToUse);
                            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
                            DataSourceUtils.releaseConnection(c, dsToUse);
                        }
                    });
                } finally {
                    if (openOuterConnection) {
                        try {
                            c.isReadOnly();
                            DataSourceUtils.releaseConnection(c, dsToUse);
                        } catch (SQLException ex) {
                        }
                    }
                }
            }
        });
        fail("Should have thrown TransactionException");
    } catch (TransactionException ex) {
    // expected
    }
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
    verify(userTransaction).begin();
    if (suspendException) {
        verify(userTransaction).rollback();
    }
    if (suspendException) {
        verify(connection, atLeastOnce()).close();
    } else {
        verify(connection, never()).close();
    }
}
Also used : JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) TransactionException(org.springframework.transaction.TransactionException) SystemException(javax.transaction.SystemException) SQLException(java.sql.SQLException) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Connection(java.sql.Connection) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) DataSource(javax.sql.DataSource)

Aggregations

TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)142 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)103 Test (org.junit.Test)90 TransactionStatus (org.springframework.transaction.TransactionStatus)71 JtaTransactionManager (org.springframework.transaction.jta.JtaTransactionManager)50 UserTransaction (javax.transaction.UserTransaction)43 SQLException (java.sql.SQLException)17 Connection (java.sql.Connection)14 TransactionSynchronization (org.springframework.transaction.support.TransactionSynchronization)13 UncategorizedSQLException (org.springframework.jdbc.UncategorizedSQLException)12 DataSource (javax.sql.DataSource)11 TransactionCallback (org.springframework.transaction.support.TransactionCallback)10 PreparedStatement (java.sql.PreparedStatement)9 TransactionManager (javax.transaction.TransactionManager)9 InOrder (org.mockito.InOrder)9 SystemException (javax.transaction.SystemException)8 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)8 TransactionSynchronizationAdapter (org.springframework.transaction.support.TransactionSynchronizationAdapter)8 DatabaseMetaData (java.sql.DatabaseMetaData)6 Savepoint (java.sql.Savepoint)6