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:org.drools.container.spring.beans.persistence.DroolsSpringJpaManager.java

public void beginCommandScopedEntityManager() {
    EntityManager cmdScopedEntityManager = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
    if (cmdScopedEntityManager == null || !cmdScopedEntityManager.isOpen()) {
        EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                .getResource("cmdEM");
        EntityManager em = null;/*from w ww . j a  v a  2 s.  co m*/
        if (emHolder == null) {
            em = this.emf.createEntityManager();
            emHolder = new EntityManagerHolder(em);
            TransactionSynchronizationManager.bindResource("cmdEM", emHolder);
        } else {
            em = emHolder.getEntityManager();
        }
        this.env.set(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, em);
    }

    this.getCommandScopedPersistenceContext().joinTransaction();
    this.appScopedEntityManager.joinTransaction();

}

From source file:org.springextensions.neodatis.NeoDatisTransactionManager.java

@Override
protected void doResume(Object transaction, Object suspendedResources) throws TransactionException {
    SuspendedResourcesHolder suspendedResourcesHolder = (SuspendedResourcesHolder) suspendedResources;
    if (TransactionSynchronizationManager.hasResource(getOdb())) {
        TransactionSynchronizationManager.unbindResource(getOdb());
    }//  w w w . ja v a  2 s .co  m
    TransactionSynchronizationManager.bindResource(getOdb(), suspendedResourcesHolder.getOdbHolder());
}

From source file:com.jaspersoft.jasperserver.test.CoreDataCreateTestNG.java

@BeforeClass()
public void onSetUp() throws Exception {
    m_logger.info("onSetUp() called");

    /*/*w  ww .j  a v a  2 s .  c o m*/
     * The TransactionSynchronizationManager work is only needed in tests to allow multiple
     * Hibernate transactions to occur. Otherwise, each "template." call is a transaction.
     * Lazy initialization of collections will not occur otherwise. In a web app, there is Spring
     * configuration to do a transaction per web request - OpenSessionInViewFilter.
     */
    Session s = m_sessionFactory.openSession();
    TransactionSynchronizationManager.bindResource(m_sessionFactory, new SessionHolder(s));
    m_template = m_jasperServerDao.getHibernateTemplate();
}

From source file:org.ops4j.orient.spring.tx.OrientTransactionManager.java

@Override
protected void doResume(Object transaction, Object suspendedResources) throws TransactionException {
    OrientTransaction tx = (OrientTransaction) transaction;
    ODatabaseInternal<?> db = tx.getDatabase();
    if (!db.isClosed()) {
        db.close();//from  w  w  w  . jav a2 s . c  o m
    }
    ODatabaseInternal<?> oldDb = (ODatabaseInternal<?>) suspendedResources;
    TransactionSynchronizationManager.bindResource(dbf, oldDb);
    ODatabaseRecordThreadLocal.INSTANCE.set((ODatabaseDocumentInternal) oldDb.getUnderlying());
}

From source file:org.motechproject.server.omod.sdsched.TxSyncManWrapperImplTest.java

public void testUnbindResource() {
    final String resourceName = "A Resource";
    final String resourceValue = "A Resource value";
    Object retVal = txTempl.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            try {
                TransactionSynchronizationManager.bindResource(resourceName, resourceValue);
                txSyncManWrapper.unbindResource(resourceName);
                return txSyncManWrapper.getResource(resourceName);
            } finally {
                TransactionSynchronizationManager.unbindResourceIfPossible(resourceName);
            }//from w w  w. j ava 2 s .  c  o  m
        }
    });
    assertNull(resourceValue, retVal);
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.ContentSourceUtils.java

/**
 * Actually obtain a XDBC Session from the given ContentSource.
 * Same as {@link #getSession}, but throwing the original XccException.
 * <p>Is aware of a corresponding Session bound to the current thread, for example
 * when using {@link ContentSourceTransactionManager}. Will bind a Session to the thread
 * if transaction synchronization is active (e.g. if in a JTA transaction).
 * <p>Directly accessed by {@link TransactionAwareContentSourceProxy}.
 * @param contentSource the ContentSource to obtain Sessions from
 * @return a XDBC Session from the given ContentSource
 * @throws XccException if thrown by XDBC methods
 * @see #doReleaseSession/*w w  w  .j a v a2  s  .c om*/
 */
public static Session doGetSession(ContentSource contentSource) throws XccException {
    Assert.notNull(contentSource, "No ContentSource specified");

    SessionHolder sesHolder = (SessionHolder) TransactionSynchronizationManager.getResource(contentSource);
    if (sesHolder != null && (sesHolder.hasSession() || sesHolder.isSynchronizedWithTransaction())) {
        sesHolder.requested();
        if (!sesHolder.hasSession()) {
            logger.debug("Fetching resumed XDBC Session from ContentSource");
            sesHolder.setSession(contentSource.newSession());
        }
        return sesHolder.getSession();
    }
    // Else we either got no holder or an empty thread-bound holder here.

    logger.debug("Fetching XDBC Session from ContentSource");
    Session ses = contentSource.newSession();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        logger.debug("Registering transaction synchronization for XDBC Session");
        // Use same Session for further XDBC actions within the transaction.
        // Thread-bound object will get removed by synchronization at transaction completion.
        SessionHolder holderToUse = sesHolder;
        if (holderToUse == null) {
            holderToUse = new SessionHolder(ses);
        } else {
            holderToUse.setSession(ses);
        }
        holderToUse.requested();
        TransactionSynchronizationManager
                .registerSynchronization(new SessionSynchronization(holderToUse, contentSource));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sesHolder) {
            TransactionSynchronizationManager.bindResource(contentSource, holderToUse);
        }
    }

    return ses;
}

From source file:org.grails.datastore.mapping.transactions.DatastoreTransactionManager.java

@Override
protected void doBegin(Object o, TransactionDefinition definition) throws TransactionException {
    TransactionObject txObject = (TransactionObject) o;

    Session session = null;/*from  ww  w.j  a v  a2s  . c o  m*/
    try {
        session = txObject.getSessionHolder().getSession();

        if (definition.isReadOnly()) {
            // Just set to NEVER in case of a new Session for this transaction.
            session.setFlushMode(FlushModeType.COMMIT);
        }

        Transaction<?> tx;
        // Register transaction timeout.
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            tx = session.beginTransaction();
            tx.setTimeout(timeout);
        } else {
            // Open a plain Datastore transaction without specified timeout.
            tx = session.beginTransaction();
        }

        // Add the Datastore transaction to the session holder.
        txObject.setTransaction(tx);

        // Bind the session holder to the thread.
        if (txObject.isNewSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getDatastore(), txObject.getSessionHolder());
        }
        txObject.getSessionHolder().setSynchronizedWithTransaction(true);
    } catch (Exception ex) {
        if (txObject.isNewSession()) {
            try {
                if (session != null && session.getTransaction().isActive()) {
                    session.getTransaction().rollback();
                }
            } catch (Throwable ex2) {
                logger.debug("Could not rollback Session after failed transaction begin", ex);
            } finally {
                DatastoreUtils.closeSession(session);
            }
        }
        throw new CannotCreateTransactionException("Could not open Datastore Session for transaction", ex);
    }
}

From source file:org.jtalks.poulpe.web.osod.OpenSessions.java

/** Binds hibernate session to current thread  
 * @param session for binding //from w  ww. j a  va 2  s.  c om
 */
@VisibleForTesting
void bindToThread(Session session) {
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}

From source file:eu.supersede.fe.multitenant.MultiJpaProvider.java

public <T extends JpaRepository<?, ?>> T getRepository(Class<T> jpaRepositoryClass, String tenant) {
    T repo = null;//  www  . j  av a 2s  .c o  m

    if (repositoriesFactory.containsKey(tenant)) {
        ContainerUtil factory = repositoriesFactory.get(tenant);
        repo = factory.jpaRepositoryFactory.getRepository(jpaRepositoryClass);

        if (!TransactionSynchronizationManager.hasResource(factory.entityManagerFactory)) {
            EntityManagerHolder emh = new EntityManagerHolder(factory.entityManager);
            TransactionSynchronizationManager.bindResource(factory.entityManagerFactory, emh);
        }
    }

    return repo;
}

From source file:org.mybatis.spring.SqlSessionUtils.java

/**
 * Register session holder if synchronization is active (i.e. a Spring TX is active).
 *
 * Note: The DataSource used by the Environment should be synchronized with the
 * transaction either through DataSourceTxMgr or another tx synchronization.
 * Further assume that if an exception is thrown, whatever started the transaction will
 * handle closing / rolling back the Connection associated with the SqlSession.
 * //from   w  w  w.  jav a2  s  .  c  om
 * @param sessionFactory sqlSessionFactory used for registration.
 * @param executorType executorType used for registration.
 * @param exceptionTranslator persistenceExceptionTranslater used for registration.
 * @param session sqlSession used for registration.
 */
private static void registerSessionHolder(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator, SqlSession session) {
    SqlSessionHolder holder;
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        Environment environment = sessionFactory.getConfiguration().getEnvironment();

        if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Registering transaction synchronization for SqlSession [" + session + "]");
            }

            holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
            TransactionSynchronizationManager.bindResource(sessionFactory, holder);
            TransactionSynchronizationManager
                    .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
            holder.setSynchronizedWithTransaction(true);
            holder.requested();
        } else {
            if (TransactionSynchronizationManager.getResource(environment.getDataSource()) == null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("SqlSession [" + session
                            + "] was not registered for synchronization because DataSource is not transactional");
                }
            } else {
                throw new TransientDataAccessResourceException(
                        "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
            }
        }
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("SqlSession [" + session
                    + "] was not registered for synchronization because synchronization is not active");
        }
    }
}