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.springframework.orm.hibernate5.SpringSessionContext.java

/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 *///w  ww  .j a v a  2 s.c  om
@Override
@SuppressWarnings("deprecation")
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
    if (value instanceof Session) {
        return (Session) value;
    } else if (value instanceof SessionHolder) {
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();
        if (!sessionHolder.isSynchronizedWithTransaction()
                && TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(
                    new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
            sessionHolder.setSynchronizedWithTransaction(true);
            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = SessionFactoryUtils.getFlushMode(session);
            if (flushMode.equals(FlushMode.MANUAL)
                    && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }
        return session;
    }

    if (this.transactionManager != null && this.jtaSessionContext != null) {
        try {
            if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) {
                Session session = this.jtaSessionContext.currentSession();
                if (TransactionSynchronizationManager.isSynchronizationActive()) {
                    TransactionSynchronizationManager
                            .registerSynchronization(new SpringFlushSynchronization(session));
                }
                return session;
            }
        } catch (SystemException ex) {
            throw new HibernateException("JTA TransactionManager found but status check failed", ex);
        }
    }

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        Session session = this.sessionFactory.openSession();
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.registerSynchronization(
                new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
        TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
        sessionHolder.setSynchronizedWithTransaction(true);
        return session;
    } else {
        throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
    }
}

From source file:org.springframework.orm.hibernate5.support.AsyncRequestInterceptor.java

public void bindSession() {
    this.timeoutInProgress = false;
    this.errorInProgress = false;
    TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder);
}

From source file:org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor.java

/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 *//*w w w  .  j  a va2s .c om*/
@Override
public void preHandle(WebRequest request) throws DataAccessException {
    String participateAttributeName = getParticipateAttributeName();

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    if (asyncManager.hasConcurrentResult()) {
        if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
            return;
        }
    }

    if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) {
        // Do not modify the Session: just mark the request accordingly.
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {
        logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
        Session session = openSession();
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder);

        AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(obtainSessionFactory(),
                sessionHolder);
        asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
        asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
    }
}

From source file:org.springframework.orm.jdo.PersistenceManagerFactoryUtils.java

/**
 * Obtain a JDO PersistenceManager via the given factory. Is aware of a
 * corresponding PersistenceManager bound to the current thread,
 * for example when using JdoTransactionManager. Will create a new
 * PersistenceManager else, if "allowCreate" is {@code true}.
 * <p>Same as {@code getPersistenceManager}, but throwing the original JDOException.
 * @param pmf PersistenceManagerFactory to create the PersistenceManager with
 * @param allowCreate if a non-transactional PersistenceManager should be created
 * when no transactional PersistenceManager can be found for the current thread
 * @return the PersistenceManager// www .ja v  a2s. c o m
 * @throws JDOException if the PersistenceManager couldn't be created
 * @throws IllegalStateException if no thread-bound PersistenceManager found and
 * "allowCreate" is {@code false}
 * @see #getPersistenceManager(javax.jdo.PersistenceManagerFactory, boolean)
 * @see JdoTransactionManager
 */
public static PersistenceManager doGetPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate)
        throws JDOException, IllegalStateException {

    Assert.notNull(pmf, "No PersistenceManagerFactory specified");

    PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager
            .getResource(pmf);
    if (pmHolder != null) {
        if (!pmHolder.isSynchronizedWithTransaction()
                && TransactionSynchronizationManager.isSynchronizationActive()) {
            pmHolder.setSynchronizedWithTransaction(true);
            TransactionSynchronizationManager
                    .registerSynchronization(new PersistenceManagerSynchronization(pmHolder, pmf, false));
        }
        return pmHolder.getPersistenceManager();
    }

    if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
        throw new IllegalStateException("No JDO PersistenceManager bound to thread, "
                + "and configuration does not allow creation of non-transactional one here");
    }

    logger.debug("Opening JDO PersistenceManager");
    PersistenceManager pm = pmf.getPersistenceManager();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        logger.debug("Registering transaction synchronization for JDO PersistenceManager");
        // Use same PersistenceManager for further JDO actions within the transaction.
        // Thread object will get removed by synchronization at transaction completion.
        pmHolder = new PersistenceManagerHolder(pm);
        pmHolder.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager
                .registerSynchronization(new PersistenceManagerSynchronization(pmHolder, pmf, true));
        TransactionSynchronizationManager.bindResource(pmf, pmHolder);
    }

    return pm;
}

From source file:org.springframework.orm.jdo.support.OpenPersistenceManagerInViewInterceptor.java

@Override
public void preHandle(WebRequest request) throws DataAccessException {
    if (TransactionSynchronizationManager.hasResource(getPersistenceManagerFactory())) {
        // Do not modify the PersistenceManager: just mark the request accordingly.
        String participateAttributeName = getParticipateAttributeName();
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {/*from  ww w . ja v  a 2s  .  co  m*/
        logger.debug("Opening JDO PersistenceManager in OpenPersistenceManagerInViewInterceptor");
        PersistenceManager pm = PersistenceManagerFactoryUtils
                .getPersistenceManager(getPersistenceManagerFactory(), true);
        TransactionSynchronizationManager.bindResource(getPersistenceManagerFactory(),
                new PersistenceManagerHolder(pm));
    }
}

From source file:org.springframework.orm.jpa.EntityManagerFactoryUtils.java

/**
 * Obtain a JPA EntityManager from the given factory. Is aware of a corresponding
 * EntityManager bound to the current thread, e.g. when using JpaTransactionManager.
 * <p>Same as {@code getEntityManager}, but throwing the original PersistenceException.
 * @param emf EntityManagerFactory to create the EntityManager with
 * @param properties the properties to be passed into the {@code createEntityManager}
 * call (may be {@code null})/* ww  w . ja  va  2s .c o  m*/
 * @param synchronizedWithTransaction whether to automatically join ongoing
 * transactions (according to the JPA 2.1 SynchronizationType rules)
 * @return the EntityManager, or {@code null} if none found
 * @throws javax.persistence.PersistenceException if the EntityManager couldn't be created
 * @see #getTransactionalEntityManager(javax.persistence.EntityManagerFactory)
 * @see JpaTransactionManager
 */
@Nullable
public static EntityManager doGetTransactionalEntityManager(EntityManagerFactory emf,
        @Nullable Map<?, ?> properties, boolean synchronizedWithTransaction) throws PersistenceException {

    Assert.notNull(emf, "No EntityManagerFactory specified");

    EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(emf);
    if (emHolder != null) {
        if (synchronizedWithTransaction) {
            if (!emHolder.isSynchronizedWithTransaction()) {
                if (TransactionSynchronizationManager.isActualTransactionActive()) {
                    // Try to explicitly synchronize the EntityManager itself
                    // with an ongoing JTA transaction, if any.
                    try {
                        emHolder.getEntityManager().joinTransaction();
                    } catch (TransactionRequiredException ex) {
                        logger.debug("Could not join transaction because none was actually active", ex);
                    }
                }
                if (TransactionSynchronizationManager.isSynchronizationActive()) {
                    Object transactionData = prepareTransaction(emHolder.getEntityManager(), emf);
                    TransactionSynchronizationManager
                            .registerSynchronization(new TransactionalEntityManagerSynchronization(emHolder,
                                    emf, transactionData, false));
                    emHolder.setSynchronizedWithTransaction(true);
                }
            }
            // Use holder's reference count to track synchronizedWithTransaction access.
            // isOpen() check used below to find out about it.
            emHolder.requested();
            return emHolder.getEntityManager();
        } else {
            // unsynchronized EntityManager demanded
            if (emHolder.isTransactionActive() && !emHolder.isOpen()) {
                if (!TransactionSynchronizationManager.isSynchronizationActive()) {
                    return null;
                }
                // EntityManagerHolder with an active transaction coming from JpaTransactionManager,
                // with no synchronized EntityManager having been requested by application code before.
                // Unbind in order to register a new unsynchronized EntityManager instead.
                TransactionSynchronizationManager.unbindResource(emf);
            } else {
                // Either a previously bound unsynchronized EntityManager, or the application
                // has requested a synchronized EntityManager before and therefore upgraded
                // this transaction's EntityManager to synchronized before.
                return emHolder.getEntityManager();
            }
        }
    } else if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        // Indicate that we can't obtain a transactional EntityManager.
        return null;
    }

    // Create a new EntityManager for use within the current transaction.
    logger.debug("Opening JPA EntityManager");
    EntityManager em = null;
    if (!synchronizedWithTransaction) {
        try {
            em = emf.createEntityManager(SynchronizationType.UNSYNCHRONIZED, properties);
        } catch (AbstractMethodError err) {
            // JPA 2.1 API available but method not actually implemented in persistence provider:
            // falling back to regular createEntityManager method.
        }
    }
    if (em == null) {
        em = (!CollectionUtils.isEmpty(properties) ? emf.createEntityManager(properties)
                : emf.createEntityManager());
    }

    // Use same EntityManager for further JPA operations within the transaction.
    // Thread-bound object will get removed by synchronization at transaction completion.
    logger.debug("Registering transaction synchronization for JPA EntityManager");
    emHolder = new EntityManagerHolder(em);
    if (synchronizedWithTransaction) {
        Object transactionData = prepareTransaction(em, emf);
        TransactionSynchronizationManager.registerSynchronization(
                new TransactionalEntityManagerSynchronization(emHolder, emf, transactionData, true));
        emHolder.setSynchronizedWithTransaction(true);
    } else {
        // Unsynchronized - just scope it for the transaction, as demanded by the JPA 2.1 spec...
        TransactionSynchronizationManager
                .registerSynchronization(new TransactionScopedEntityManagerSynchronization(emHolder, emf));
    }
    TransactionSynchronizationManager.bindResource(emf, emHolder);

    return em;
}

From source file:org.springframework.orm.jpa.support.AsyncRequestInterceptor.java

public void bindEntityManager() {
    this.timeoutInProgress = false;
    this.errorInProgress = false;
    TransactionSynchronizationManager.bindResource(this.emFactory, this.emHolder);
}

From source file:org.springframework.orm.ojb.OjbFactoryUtils.java

/**
 * Get an OJB PersistenceBroker for the given PBKey. Is aware of a
 * corresponding PersistenceBroker bound to the current thread, for
 * example when using PersistenceBrokerTransactionManager. Will
 * create a new PersistenceBroker else, if allowCreate is true.
 * @param pbKey PBKey to create the PersistenceBroker for
 * @param allowCreate if a non-transactional PersistenceBroker should be created
 * when no transactional PersistenceBroker can be found for the current thread
 * @return the PersistenceBroker//  ww  w  .j  av  a2s .  co  m
 * @throws DataAccessResourceFailureException if the PersistenceBroker couldn't be created
 * @throws IllegalStateException if no thread-bound PersistenceBroker found and allowCreate false
 */
public static PersistenceBroker getPersistenceBroker(PBKey pbKey, boolean allowCreate)
        throws DataAccessResourceFailureException, IllegalStateException {

    PersistenceBrokerHolder pbHolder = (PersistenceBrokerHolder) TransactionSynchronizationManager
            .getResource(pbKey);
    if (pbHolder != null) {
        return pbHolder.getPersistenceBroker();
    }

    if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
        throw new IllegalStateException("No OJB PersistenceBroker bound to thread, "
                + "and configuration does not allow creation of non-transactional one here");
    }

    try {
        logger.debug("Opening OJB PersistenceBroker");
        PersistenceBroker pb = PersistenceBrokerFactory.createPersistenceBroker(pbKey);

        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            logger.debug("Registering transaction synchronization for OJB PersistenceBroker");
            // Use same PersistenceBroker for further OJB actions within the transaction.
            // Thread object will get removed by synchronization at transaction completion.
            pbHolder = new PersistenceBrokerHolder(pb);
            pbHolder.setSynchronizedWithTransaction(true);
            TransactionSynchronizationManager
                    .registerSynchronization(new PersistenceBrokerSynchronization(pbHolder, pbKey));
            TransactionSynchronizationManager.bindResource(pbKey, pbHolder);
        }

        return pb;
    } catch (OJBRuntimeException ex) {
        throw new DataAccessResourceFailureException("Could not open OJB PersistenceBroker", ex);
    }
}

From source file:org.springframework.orm.toplink.SessionFactoryUtils.java

/**
 * Get a TopLink Session for the given SessionFactory. Is aware of and will
 * return any existing corresponding Session bound to the current thread, for
 * example when using TopLinkTransactionManager. Will create a new Session
 * otherwise, if "allowCreate" is <code>true</code>.
 * <p>Same as <code>getSession</code>, but throwing the original TopLinkException.
 * @param sessionFactory TopLink SessionFactory to create the session with
 * @param allowCreate if a non-transactional Session should be created when no
 * transactional Session can be found for the current thread
 * @return the TopLink Session/*w w  w  .  j  av a 2  s .c o m*/
 * @throws TopLinkException if the Session couldn't be created
 * @throws IllegalStateException if no thread-bound Session found and
 * "allowCreate" is <code>false</code>
 * @see #releaseSession
 * @see TopLinkTemplate
 */
public static Session doGetSession(SessionFactory sessionFactory, boolean allowCreate)
        throws TopLinkException, IllegalStateException {

    Assert.notNull(sessionFactory, "No SessionFactory specified");

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null) {
        return sessionHolder.getSession();
    }

    if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
        throw new IllegalStateException("No TopLink Session bound to thread, "
                + "and configuration does not allow creation of non-transactional one here");
    }

    logger.debug("Creating TopLink Session");
    Session session = sessionFactory.createSession();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        logger.debug("Registering new Spring transaction synchronization for new TopLink Session");
        // Use same Session for further TopLink actions within the transaction.
        // Thread object will get removed by synchronization at transaction completion.
        sessionHolder = new SessionHolder(session);
        sessionHolder.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager
                .registerSynchronization(new SessionSynchronization(sessionHolder, sessionFactory));
        TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
    }

    return session;
}

From source file:org.springframework.transaction.compensating.support.AbstractCompensatingTransactionManagerDelegate.java

public void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
    try {/*from w w w.  j  a  va  2 s .  co m*/
        CompensatingTransactionObject txObject = (CompensatingTransactionObject) transaction;
        if (txObject.getHolder() == null) {
            CompensatingTransactionHolderSupport contextHolder = getNewHolder();
            txObject.setHolder(contextHolder);

            TransactionSynchronizationManager.bindResource(getTransactionSynchronizationKey(), contextHolder);
        }
    } catch (Exception e) {
        throw new CannotCreateTransactionException("Could not create DirContext instance for transaction", e);
    }
}