Example usage for org.springframework.transaction.support TransactionSynchronizationManager bindResource

List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager bindResource

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionSynchronizationManager bindResource.

Prototype

public static void bindResource(Object key, Object value) throws IllegalStateException 

Source Link

Document

Bind the given resource for the given key to the current thread.

Usage

From source file:fr.certu.chouette.command.Command.java

/**
 * @param factory//from  ww w.  j ava 2s.co m
 */
public static void initDao() {
    if (dao) {
        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
        SessionFactory sessionFactory = (SessionFactory) factory.getBean("sessionFactory");
        Session session = SessionFactoryUtils.getSession(sessionFactory, true);
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
    }
}

From source file:org.guzz.web.context.spring.TransactionManagerUtils.java

/**
 * Get a Guzz WriteTranSession for the given TransactionManager. Is aware of and will
 * return any existing corresponding Session bound to the current thread, for
 * example when using {@link GuzzTransactionManager}. Will create a new
 * Session otherwise, if "allowCreate" is <code>true</code>.
 * <p>Same as {@link #getSession}, but throwing the original GuzzException.
 * @param transactionManager Guzz TransactionManager to create the session with
 * @param entityInterceptor Guzz entity interceptor, or <code>null</code> if none
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be <code>null</code>)
 * @param allowCreate whether a non-transactional Session should be created
 * when no transactional Session can be found for the current thread
 * @return the Guzz WriteTranSession//from w w w.  ja v a2 s .  co m
 * @throws GuzzException if the Session couldn't be created
 * @throws IllegalStateException if no thread-bound Session found and
 * "allowCreate" is <code>false</code>
 */
private static WriteTranSession doGetSession(TransactionManager transactionManager)
        throws GuzzException, IllegalStateException {
    Assert.notNull(transactionManager, "No TransactionManager specified");
    WriteTranSession session = null;

    WriteTranSessionHolder writeTranSessionHolder = (WriteTranSessionHolder) TransactionSynchronizationManager
            .getResource(transactionManager);
    if (writeTranSessionHolder != null) {
        // pre-bound Guzz WriteTranSession
        session = writeTranSessionHolder.getWriteTranSession();
    } else {
        //????spring?????bug
        logger.debug("Opening Guzz WriteTranSession");
        session = transactionManager.openRWTran(false);

        // Use same Session for further Guzz actions within the transaction.
        // Thread object will get removed by synchronization at transaction completion.
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            // We're within a Spring-managed transaction, possibly from JtaTransactionManager.
            logger.debug("Registering Spring transaction synchronization for new Guzz WriteTranSession");
            writeTranSessionHolder = new WriteTranSessionHolder(session);

            TransactionSynchronizationManager.registerSynchronization(
                    new SpringSessionSynchronization(writeTranSessionHolder, transactionManager, true));

            TransactionSynchronizationManager.bindResource(transactionManager, writeTranSessionHolder);
            writeTranSessionHolder.setSynchronizedWithTransaction(true);
        }

        // Check whether we are allowed to return the Session.
        if (!isSessionTransactional(session, transactionManager)) {
            closeSession(session);
            throw new IllegalStateException("No Guzz WriteTranSession bound to thread here");
        }
    }

    if (writeTranSessionHolder.hasTimeout()) {
        session.setQueryTimeoutInSeconds(writeTranSessionHolder.getTimeToLiveInSeconds());
    }

    return session;
}

From source file:org.alfresco.util.transaction.TransactionSupportUtil.java

/**
 * Helper method to rebind the synchronization to the transaction
 *
 * @param txnSynch TransactionSynchronizationImpl
 *//*w w  w .  java 2 s .co  m*/
private static void rebindSynchronization(TransactionSynchronizationImpl txnSynch) {
    TransactionSynchronizationManager.bindResource(RESOURCE_KEY_TXN_SYNCH, txnSynch);
    if (logger.isDebugEnabled()) {
        logger.debug("Bound (rebind) txn synch: " + txnSynch);
    }
}

From source file:org.fornax.cartridges.sculptor.framework.web.jpa.JpaFlowExecutionListener.java

private void bind(EntityManager em) {
    TransactionSynchronizationManager.bindResource(entityManagerFactory, new EntityManagerHolder(em));
}

From source file:org.fornax.cartridges.sculptor.framework.web.hibernate.OpenHibernateSessionInConversationListener.java

private void bind(Session session) {
    if (!TransactionSynchronizationManager.hasResource(sessionFactory)) {
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
    }/* w ww.  j a v  a 2  s. c o m*/
}

From source file:org.cfr.capsicum.datasource.CayenneTransactionManager.java

/**
 * This implementation sets the isolation level but ignores the timeout.
 *//*  w w  w.j  a v  a 2  s.c  om*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    CayenneTransactionObject txObject = (CayenneTransactionObject) transaction;
    Connection con = null;

    try {
        if (txObject.getConnectionHolder() == null
                || txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
            Connection newCon = this.dataSource.getConnection();
            if (logger.isDebugEnabled()) {
                logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
            }
            ObjectContext context = null;
            if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
                Injector injector = this.cayenneRuntime.getInjector();
                context = injector.getInstance(ObjectContextFactory.class).createContext();
            } else {
                context = BaseContext.getThreadObjectContext();
            }
            txObject.setConnectionHolder(new CayenneConnectionHolder(newCon, context), true);
            BaseContext.bindThreadObjectContext(context);
        }

        txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
        con = txObject.getConnectionHolder().getConnection();

        Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
        txObject.setPreviousIsolationLevel(previousIsolationLevel);

        // Switch to manual commit if necessary. This is very expensive in
        // some
        // JDBC drivers,
        // so we don't want to do it unnecessarily (for example if we've
        // explicitly
        // configured the connection pool to set it already).
        if (con.getAutoCommit()) {
            txObject.setMustRestoreAutoCommit(true);
            if (logger.isDebugEnabled()) {
                logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
            }
            con.setAutoCommit(false);
        }
        txObject.getConnectionHolderEx().setTransactionActive(true);

        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewConnectionHolder()) {
            TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());
        }
    }

    catch (SQLException ex) {
        DataSourceUtils.releaseConnection(con, this.dataSource);
        throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction",
                exceptionTranslator.convertJdbcAccessException(ex));
    }
}

From source file:org.grails.orm.hibernate.GrailsSessionContext.java

protected void registerJtaSynchronization(Session session, SessionHolder sessionHolder) {

    // JTA synchronization is only possible with a javax.transaction.TransactionManager.
    // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
    // in Hibernate configuration, it will contain a TransactionManager reference.
    TransactionManager jtaTm = getJtaTransactionManager(session);
    if (jtaTm == null) {
        return;//ww  w .j a va  2  s .c  o  m
    }

    try {
        Transaction jtaTx = jtaTm.getTransaction();
        if (jtaTx == null) {
            return;
        }

        int jtaStatus = jtaTx.getStatus();
        if (jtaStatus != Status.STATUS_ACTIVE && jtaStatus != Status.STATUS_MARKED_ROLLBACK) {
            return;
        }

        LOG.debug("Registering JTA transaction synchronization for new Hibernate Session");
        SessionHolder holderToUse = sessionHolder;
        // Register JTA Transaction with existing SessionHolder.
        // Create a new SessionHolder if none existed before.
        if (holderToUse == null) {
            holderToUse = new SessionHolder(session);
        } else {
            // it's up to the caller to manage concurrent sessions
            // holderToUse.addSession(session);
        }
        jtaTx.registerSynchronization(
                new SpringJtaSynchronizationAdapter(createSpringSessionSynchronization(holderToUse), jtaTm));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sessionHolder) {
            TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
        }
    } catch (Throwable ex) {
        throw new DataAccessResourceFailureException(
                "Could not register synchronization with JTA TransactionManager", ex);
    }
}

From source file:org.guzz.web.context.spring.GuzzTransactionManager.java

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    GuzzTransactionObject txObject = (GuzzTransactionObject) transaction;

    //TODO: checkout the outside DataSourceTransactionManager 
    //      if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
    //         throw new IllegalTransactionStateException(
    //               "Pre-bound JDBC Connection found! GuzzTransactionManager does not support " +
    //               "running within DataSourceTransactionManager if told to manage the DataSource itself. ") ;
    //      }// w ww  .  j a v  a  2 s  .  c  om

    WriteTranSession writeTranSession = null;

    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            writeTranSession = getTransactionManager().openRWTran(false);

            if (logger.isDebugEnabled()) {
                logger.debug("Opened new Session [" + TransactionManagerUtils.toString(writeTranSession)
                        + "] for Guzz transaction");
            }
            txObject.setWriteTranSession(writeTranSession);
        }

        writeTranSession = txObject.getSessionHolder().getWriteTranSession();

        if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
            // We should set a specific isolation level but are not allowed to...
            IsolationsSavePointer oldSavePointer = writeTranSession
                    .setTransactionIsolation(definition.getIsolationLevel());

            txObject.setIsolationsSavePointer(oldSavePointer);
        }

        // Register transaction timeout.
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getSessionHolder().setTimeoutInSeconds(timeout);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewWriteTranSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getTransactionManager(),
                    txObject.getSessionHolder());
        }
        txObject.getSessionHolder().setSynchronizedWithTransaction(true);

    } catch (Exception ex) {
        if (txObject.isNewWriteTranSession()) {
            try {
                if (writeTranSession != null) {
                    //TransactionIsolation?????
                    writeTranSession.rollback();
                }
            } catch (Throwable ex2) {
                logger.debug("Could not rollback WriteTranSession after failed transaction begin", ex);
            } finally {
                TransactionManagerUtils.closeSession(writeTranSession);
            }
        }
        throw new CannotCreateTransactionException("Could not open Guzz WriteTranSession for transaction", ex);
    }
}

From source file:fr.certu.chouette.gui.command.Command.java

/**
 * @param factory/*  w w w  . j a  va  2  s .  c om*/
 */
public static void initDao() {
    ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
    SessionFactory sessionFactory = (SessionFactory) factory.getBean("sessionFactory");
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}