Search in sources :

Example 1 with JtaTransactionManager

use of org.springframework.transaction.jta.JtaTransactionManager 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 2 with JtaTransactionManager

use of org.springframework.transaction.jta.JtaTransactionManager 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)

Example 3 with JtaTransactionManager

use of org.springframework.transaction.jta.JtaTransactionManager in project spring-framework by spring-projects.

the class DataSourceJtaTransactionTests method doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction.

private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(final boolean requiresNew, boolean notSupported) throws Exception {
    if (notSupported) {
        given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
        given(transactionManager.suspend()).willReturn(transaction);
    } else {
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
    }
    final DataSource dataSource = mock(DataSource.class);
    final Connection connection1 = mock(Connection.class);
    final Connection connection2 = mock(Connection.class);
    given(dataSource.getConnection()).willReturn(connection1, connection2);
    final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(notSupported ? TransactionDefinition.PROPAGATION_NOT_SUPPORTED : TransactionDefinition.PROPAGATION_SUPPORTS);
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(connection1, DataSourceUtils.getConnection(dataSource));
            assertSame(connection1, DataSourceUtils.getConnection(dataSource));
            TransactionTemplate tt2 = new TransactionTemplate(ptm);
            tt2.setPropagationBehavior(requiresNew ? TransactionDefinition.PROPAGATION_REQUIRES_NEW : TransactionDefinition.PROPAGATION_REQUIRED);
            tt2.execute(new TransactionCallbackWithoutResult() {

                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
                    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                    assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
                    assertSame(connection2, DataSourceUtils.getConnection(dataSource));
                    assertSame(connection2, DataSourceUtils.getConnection(dataSource));
                }
            });
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(connection1, DataSourceUtils.getConnection(dataSource));
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    verify(userTransaction).begin();
    verify(userTransaction).commit();
    if (notSupported) {
        verify(transactionManager).resume(transaction);
    }
    verify(connection2).close();
    verify(connection1).close();
}
Also used : JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) Connection(java.sql.Connection) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) DataSource(javax.sql.DataSource)

Example 4 with JtaTransactionManager

use of org.springframework.transaction.jta.JtaTransactionManager in project spring-framework by spring-projects.

the class DataSourceJtaTransactionTests method testJtaTransactionWithIsolationLevelDataSourceAdapter.

@Test
public void testJtaTransactionWithIsolationLevelDataSourceAdapter() throws Exception {
    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
    final IsolationLevelDataSourceAdapter dsToUse = new IsolationLevelDataSourceAdapter();
    dsToUse.setTargetDataSource(dataSource);
    dsToUse.afterPropertiesSet();
    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
    ptm.setAllowCustomIsolationLevels(true);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Connection c = DataSourceUtils.getConnection(dsToUse);
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(connection, c);
            DataSourceUtils.releaseConnection(c, dsToUse);
        }
    });
    tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
    tt.setReadOnly(true);
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Connection c = DataSourceUtils.getConnection(dsToUse);
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(connection, c);
            DataSourceUtils.releaseConnection(c, dsToUse);
        }
    });
    verify(userTransaction, times(2)).begin();
    verify(userTransaction, times(2)).commit();
    verify(connection).setReadOnly(true);
    verify(connection).setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
    verify(connection, times(2)).close();
}
Also used : JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Connection(java.sql.Connection) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.Test)

Example 5 with JtaTransactionManager

use of org.springframework.transaction.jta.JtaTransactionManager in project spring-framework by spring-projects.

the class LocalSessionFactoryBuilder method setJtaTransactionManager.

/**
	 * Set the Spring {@link JtaTransactionManager} or the JTA {@link TransactionManager}
	 * to be used with Hibernate, if any. Allows for using a Spring-managed transaction
	 * manager for Hibernate 5's session and cache synchronization, with the
	 * "hibernate.transaction.jta.platform" automatically set to it.
	 * <p>A passed-in Spring {@link JtaTransactionManager} needs to contain a JTA
	 * {@link TransactionManager} reference to be usable here, except for the WebSphere
	 * case where we'll automatically set {@code WebSphereExtendedJtaPlatform} accordingly.
	 * <p>Note: If this is set, the Hibernate settings should not contain a JTA platform
	 * setting to avoid meaningless double configuration.
	 */
public LocalSessionFactoryBuilder setJtaTransactionManager(Object jtaTransactionManager) {
    Assert.notNull(jtaTransactionManager, "Transaction manager reference must not be null");
    if (jtaTransactionManager instanceof JtaTransactionManager) {
        boolean webspherePresent = ClassUtils.isPresent("com.ibm.wsspi.uow.UOWManager", getClass().getClassLoader());
        if (webspherePresent) {
            getProperties().put(AvailableSettings.JTA_PLATFORM, "org.hibernate.engine.transaction.jta.platform.internal.WebSphereExtendedJtaPlatform");
        } else {
            JtaTransactionManager jtaTm = (JtaTransactionManager) jtaTransactionManager;
            if (jtaTm.getTransactionManager() == null) {
                throw new IllegalArgumentException("Can only apply JtaTransactionManager which has a TransactionManager reference set");
            }
            getProperties().put(AvailableSettings.JTA_PLATFORM, new ConfigurableJtaPlatform(jtaTm.getTransactionManager(), jtaTm.getUserTransaction(), jtaTm.getTransactionSynchronizationRegistry()));
        }
    } else if (jtaTransactionManager instanceof TransactionManager) {
        getProperties().put(AvailableSettings.JTA_PLATFORM, new ConfigurableJtaPlatform((TransactionManager) jtaTransactionManager, null, null));
    } else {
        throw new IllegalArgumentException("Unknown transaction manager type: " + jtaTransactionManager.getClass().getName());
    }
    // Hibernate 5.1/5.2: manually enforce connection release mode AFTER_STATEMENT (the JTA default)
    try {
        // Try Hibernate 5.2
        AvailableSettings.class.getField("CONNECTION_HANDLING");
        getProperties().put("hibernate.connection.handling_mode", "DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT");
    } catch (NoSuchFieldException ex) {
        // Try Hibernate 5.1
        try {
            AvailableSettings.class.getField("ACQUIRE_CONNECTIONS");
            getProperties().put("hibernate.connection.release_mode", "AFTER_STATEMENT");
        } catch (NoSuchFieldException ex2) {
        // on Hibernate 5.0.x or lower - no need to change the default there
        }
    }
    return this;
}
Also used : JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) TransactionManager(javax.transaction.TransactionManager) AvailableSettings(org.hibernate.cfg.AvailableSettings)

Aggregations

JtaTransactionManager (org.springframework.transaction.jta.JtaTransactionManager)57 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)50 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)50 Test (org.junit.Test)49 UserTransaction (javax.transaction.UserTransaction)47 TransactionSynchronization (org.springframework.transaction.support.TransactionSynchronization)13 TransactionManager (javax.transaction.TransactionManager)11 SystemException (javax.transaction.SystemException)8 Connection (java.sql.Connection)7 TransactionStatus (org.springframework.transaction.TransactionStatus)7 TransactionSynchronizationAdapter (org.springframework.transaction.support.TransactionSynchronizationAdapter)7 MockJtaTransaction (org.springframework.tests.transaction.MockJtaTransaction)6 Transaction (javax.transaction.Transaction)5 DataSource (javax.sql.DataSource)4 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)4 ExpectedLookupTemplate (org.springframework.tests.mock.jndi.ExpectedLookupTemplate)3 SQLException (java.sql.SQLException)2 HeuristicRollbackException (javax.transaction.HeuristicRollbackException)2 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)2 JtaTransactionObject (org.springframework.transaction.jta.JtaTransactionObject)2