Search in sources :

Example 6 with ConnectionHolder

use of org.springframework.jdbc.datasource.ConnectionHolder in project spring-framework by spring-projects.

the class JpaTransactionManager method doBegin.

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    JpaTransactionObject txObject = (JpaTransactionObject) transaction;
    if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
        throw new IllegalTransactionStateException("Pre-bound JDBC Connection found! JpaTransactionManager does not support " + "running within DataSourceTransactionManager if told to manage the DataSource itself. " + "It is recommended to use a single JpaTransactionManager for all transactions " + "on a single DataSource, no matter whether JPA or JDBC access.");
    }
    try {
        if (txObject.getEntityManagerHolder() == null || txObject.getEntityManagerHolder().isSynchronizedWithTransaction()) {
            EntityManager newEm = createEntityManagerForTransaction();
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new EntityManager [" + newEm + "] for JPA transaction");
            }
            txObject.setEntityManagerHolder(new EntityManagerHolder(newEm), true);
        }
        EntityManager em = txObject.getEntityManagerHolder().getEntityManager();
        // Delegate to JpaDialect for actual transaction begin.
        final int timeoutToUse = determineTimeout(definition);
        Object transactionData = getJpaDialect().beginTransaction(em, new DelegatingTransactionDefinition(definition) {

            @Override
            public int getTimeout() {
                return timeoutToUse;
            }
        });
        txObject.setTransactionData(transactionData);
        // Register transaction timeout.
        if (timeoutToUse != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getEntityManagerHolder().setTimeoutInSeconds(timeoutToUse);
        }
        // Register the JPA EntityManager's JDBC Connection for the DataSource, if set.
        if (getDataSource() != null) {
            ConnectionHandle conHandle = getJpaDialect().getJdbcConnection(em, definition.isReadOnly());
            if (conHandle != null) {
                ConnectionHolder conHolder = new ConnectionHolder(conHandle);
                if (timeoutToUse != TransactionDefinition.TIMEOUT_DEFAULT) {
                    conHolder.setTimeoutInSeconds(timeoutToUse);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Exposing JPA transaction as JDBC transaction [" + conHolder.getConnectionHandle() + "]");
                }
                TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
                txObject.setConnectionHolder(conHolder);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Not exposing JPA transaction [" + em + "] as JDBC transaction because " + "JpaDialect [" + getJpaDialect() + "] does not support JDBC Connection retrieval");
                }
            }
        }
        // Bind the entity manager holder to the thread.
        if (txObject.isNewEntityManagerHolder()) {
            TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), txObject.getEntityManagerHolder());
        }
        txObject.getEntityManagerHolder().setSynchronizedWithTransaction(true);
    } catch (TransactionException ex) {
        closeEntityManagerAfterFailedBegin(txObject);
        throw ex;
    } catch (Throwable ex) {
        closeEntityManagerAfterFailedBegin(txObject);
        throw new CannotCreateTransactionException("Could not open JPA EntityManager for transaction", ex);
    }
}
Also used : DelegatingTransactionDefinition(org.springframework.transaction.support.DelegatingTransactionDefinition) ConnectionHandle(org.springframework.jdbc.datasource.ConnectionHandle) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) IllegalTransactionStateException(org.springframework.transaction.IllegalTransactionStateException) ConnectionHolder(org.springframework.jdbc.datasource.ConnectionHolder) EntityManager(javax.persistence.EntityManager) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) TransactionException(org.springframework.transaction.TransactionException)

Example 7 with ConnectionHolder

use of org.springframework.jdbc.datasource.ConnectionHolder in project spring-framework by spring-projects.

the class StoredProcedureTests method testAddInvoicesWithinTransaction.

@Test
public void testAddInvoicesWithinTransaction() throws Exception {
    given(callableStatement.execute()).willReturn(false);
    given(callableStatement.getUpdateCount()).willReturn(-1);
    given(callableStatement.getObject(3)).willReturn(4);
    given(connection.prepareCall("{call " + AddInvoice.SQL + "(?, ?, ?)}")).willReturn(callableStatement);
    TransactionSynchronizationManager.bindResource(dataSource, new ConnectionHolder(connection));
    try {
        testAddInvoice(1106, 3);
        verify(callableStatement).setObject(1, 1106, Types.INTEGER);
        verify(callableStatement).setObject(2, 3, Types.INTEGER);
        verify(callableStatement).registerOutParameter(3, Types.INTEGER);
        verify(connection, never()).close();
    } finally {
        TransactionSynchronizationManager.unbindResource(dataSource);
        connection.close();
    }
}
Also used : ConnectionHolder(org.springframework.jdbc.datasource.ConnectionHolder) Test(org.junit.Test)

Aggregations

ConnectionHolder (org.springframework.jdbc.datasource.ConnectionHolder)7 Session (org.hibernate.Session)2 CannotCreateTransactionException (org.springframework.transaction.CannotCreateTransactionException)2 IllegalTransactionStateException (org.springframework.transaction.IllegalTransactionStateException)2 Connection (java.sql.Connection)1 EntityManager (javax.persistence.EntityManager)1 FlushMode (org.hibernate.FlushMode)1 HibernateException (org.hibernate.HibernateException)1 Interceptor (org.hibernate.Interceptor)1 Transaction (org.hibernate.Transaction)1 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)1 Test (org.junit.Test)1 DataAccessResourceFailureException (org.springframework.dao.DataAccessResourceFailureException)1 ConnectionHandle (org.springframework.jdbc.datasource.ConnectionHandle)1 InvalidIsolationLevelException (org.springframework.transaction.InvalidIsolationLevelException)1 TransactionException (org.springframework.transaction.TransactionException)1 DelegatingTransactionDefinition (org.springframework.transaction.support.DelegatingTransactionDefinition)1