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

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

Introduction

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

Prototype

@Nullable
public static Object getResource(Object key) 

Source Link

Document

Retrieve a resource for the given key that is bound to the current thread.

Usage

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

/**
 * Get a Hibernate Session for the given SessionFactory. Is aware of and will
 * return any existing corresponding Session bound to the current thread, for
 * example when using {@link HibernateTransactionManager}. Will create a new
 * Session otherwise, if "allowCreate" is <code>true</code>.
 * @param sessionFactory Hibernate SessionFactory to create the session with
 * @param entityInterceptor Hibernate entity interceptor, or <code>null</code> if none
 * @param jdbcExceptionTranslator SQLExceptionTranslator 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 Hibernate Session//from   w w w  .ja  v a  2  s  .com
 * @throws DataAccessResourceFailureException if the Session couldn't be created
 * @throws IllegalStateException if no thread-bound Session found and
 * "allowCreate" is <code>false</code>
 */
private static Session getSession(SessionFactory sessionFactory, Interceptor entityInterceptor,
        SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate)
        throws DataAccessResourceFailureException, IllegalStateException {

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

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && !sessionHolder.isEmpty()) {
        // pre-bound Hibernate Session
        Session session = null;
        if (TransactionSynchronizationManager.isSynchronizationActive()
                && sessionHolder.doesNotHoldNonDefaultSession()) {
            // Spring transaction management is active ->
            // register pre-bound Session with it for transactional flushing.
            session = sessionHolder.getValidatedSession();
            if (!sessionHolder.isSynchronizedWithTransaction()) {
                logger.debug("Registering Spring transaction synchronization for existing Hibernate Session");
                TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(
                        sessionHolder, sessionFactory, jdbcExceptionTranslator, false));
                sessionHolder.setSynchronizedWithTransaction(true);
                // Switch to FlushMode.AUTO if we're not within a read-only transaction.
                FlushMode flushMode = session.getFlushMode();
                if (FlushMode.NEVER.equals(flushMode)
                        && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                    session.setFlushMode(FlushMode.AUTO);
                    sessionHolder.setPreviousFlushMode(flushMode);
                }
            }
        } else {
            // No Spring transaction management active -> try JTA transaction synchronization.
            session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator);
        }
        if (session != null) {
            return session;
        }
    }

    try {
        logger.debug("Opening Hibernate Session");
        Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor)
                : sessionFactory.openSession());

        // Set Session to FlushMode.NEVER if we're within a read-only transaction.
        // Use same Session for further Hibernate 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 Hibernate Session");
            SessionHolder holderToUse = sessionHolder;
            if (holderToUse == null) {
                holderToUse = new SessionHolder(session);
            } else {
                holderToUse.addSession(session);
            }
            if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.NEVER);
            }
            TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(
                    holderToUse, sessionFactory, jdbcExceptionTranslator, true));
            holderToUse.setSynchronizedWithTransaction(true);
            if (holderToUse != sessionHolder) {
                TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
            }
        } else {
            // No Spring transaction management active -> try JTA transaction synchronization.
            registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder);
        }

        // Check whether we are allowed to return the Session.
        if (!allowCreate && !isSessionTransactional(session, sessionFactory)) {
            doClose(session);
            throw new IllegalStateException("No Hibernate Session bound to thread, "
                    + "and configuration does not allow creation of non-transactional one here");
        }

        return session;
    } catch (HibernateException ex) {
        throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
    }
}

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

/**
 * Get a new Hibernate Session from the given SessionFactory.
 * Will return a new Session even if there already is a pre-bound
 * Session for the given SessionFactory.
 * <p>Within a transaction, this method will create a new Session
 * that shares the transaction's JDBC Connection. More specifically,
 * it will use the same JDBC Connection as the pre-bound Hibernate Session.
 * @param sessionFactory Hibernate SessionFactory to create the session with
 * @param entityInterceptor Hibernate entity interceptor, or <code>null</code> if none
 * @return the new Session/*from   www  .  ja  va  2  s . c om*/
 */
public static Session getNewSession(SessionFactory sessionFactory, Interceptor entityInterceptor) {
    Assert.notNull(sessionFactory, "No SessionFactory specified");

    try {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
                .getResource(sessionFactory);
        if (sessionHolder != null && !sessionHolder.isEmpty()) {
            if (entityInterceptor != null) {
                return sessionFactory.openSession(sessionHolder.getAnySession().connection(),
                        entityInterceptor);
            } else {
                return sessionFactory.openSession(sessionHolder.getAnySession().connection());
            }
        } else {
            if (entityInterceptor != null) {
                return sessionFactory.openSession(entityInterceptor);
            } else {
                return sessionFactory.openSession();
            }
        }
    } catch (HibernateException ex) {
        throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
    }
}

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

/**
 * Return whether the given Hibernate Session is transactional, that is,
 * bound to the current thread by Spring's transaction facilities.
 * @param session the Hibernate Session to check
 * @param sessionFactory Hibernate SessionFactory that the Session was created with
 * (may be <code>null</code>)
 * @return whether the Session is transactional
 *//*  ww w.jav  a  2s. co  m*/
public static boolean isSessionTransactional(Session session, SessionFactory sessionFactory) {
    if (sessionFactory == null) {
        return false;
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    return (sessionHolder != null && sessionHolder.containsSession(session));
}

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

/**
 * Apply the current transaction timeout, if any, to the given
 * Hibernate Query object./*from ww w.  ja  v a2 s .c  om*/
 * @param query the Hibernate Query object
 * @param sessionFactory Hibernate SessionFactory that the Query was created for
 * (may be <code>null</code>)
 * @see net.sf.hibernate.Query#setTimeout
 */
public static void applyTransactionTimeout(Query query, SessionFactory sessionFactory) {
    Assert.notNull(query, "No Query object specified");
    if (sessionFactory != null) {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
                .getResource(sessionFactory);
        if (sessionHolder != null && sessionHolder.hasTimeout()) {
            query.setTimeout(sessionHolder.getTimeToLiveInSeconds());
        }
    }
}

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

/**
 * Apply the current transaction timeout, if any, to the given
 * Hibernate Criteria object.//from w  w w.j  a v a2 s. c  o m
 * @param criteria the Hibernate Criteria object
 * @param sessionFactory Hibernate SessionFactory that the Criteria was created for
 * @see net.sf.hibernate.Criteria#setTimeout
 */
public static void applyTransactionTimeout(Criteria criteria, SessionFactory sessionFactory) {
    Assert.notNull(criteria, "No Criteria object specified");
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}

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

/**
 * Get a Hibernate Session for the given SessionFactory. Is aware of and will
 * return any existing corresponding Session bound to the current thread, for
 * example when using {@link HibernateTransactionManager}. Will create a new
 * Session otherwise, if "allowCreate" is {@code true}.
 * <p>Same as {@link #getSession}, but throwing the original HibernateException.
 * @param sessionFactory Hibernate SessionFactory to create the session with
 * @param entityInterceptor Hibernate entity interceptor, or {@code null} if none
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be {@code null})
 * @param allowCreate whether a non-transactional Session should be created
 * when no transactional Session can be found for the current thread
 * @return the Hibernate Session//  w w w  .  java  2 s .co  m
 * @throws HibernateException if the Session couldn't be created
 * @throws IllegalStateException if no thread-bound Session found and
 * "allowCreate" is {@code false}
 */
private static Session doGetSession(SessionFactory sessionFactory, Interceptor entityInterceptor,
        SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate)
        throws HibernateException, IllegalStateException {

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

    Object resource = TransactionSynchronizationManager.getResource(sessionFactory);
    if (resource instanceof Session) {
        return (Session) resource;
    }
    SessionHolder sessionHolder = (SessionHolder) resource;
    if (sessionHolder != null && !sessionHolder.isEmpty()) {
        // pre-bound Hibernate Session
        Session session = null;
        if (TransactionSynchronizationManager.isSynchronizationActive()
                && sessionHolder.doesNotHoldNonDefaultSession()) {
            // Spring transaction management is active ->
            // register pre-bound Session with it for transactional flushing.
            session = sessionHolder.getValidatedSession();
            if (session != null && !sessionHolder.isSynchronizedWithTransaction()) {
                logger.debug("Registering Spring transaction synchronization for existing Hibernate Session");
                TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(
                        sessionHolder, sessionFactory, jdbcExceptionTranslator, 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 = session.getFlushMode();
                if (flushMode.lessThan(FlushMode.COMMIT)
                        && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                    session.setFlushMode(FlushMode.AUTO);
                    sessionHolder.setPreviousFlushMode(flushMode);
                }
            }
        } else {
            // No Spring transaction management active -> try JTA transaction synchronization.
            session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator);
        }
        if (session != null) {
            return session;
        }
    }

    logger.debug("Opening Hibernate Session");
    Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor)
            : sessionFactory.openSession());

    // Use same Session for further Hibernate 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 Hibernate Session");
        SessionHolder holderToUse = sessionHolder;
        if (holderToUse == null) {
            holderToUse = new SessionHolder(session);
        } else {
            holderToUse.addSession(session);
        }
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        TransactionSynchronizationManager.registerSynchronization(
                new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sessionHolder) {
            TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
        }
    } else {
        // No Spring transaction management active -> try JTA transaction synchronization.
        registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder);
    }

    // Check whether we are allowed to return the Session.
    if (!allowCreate && !isSessionTransactional(session, sessionFactory)) {
        closeSession(session);
        throw new IllegalStateException("No Hibernate Session bound to thread, "
                + "and configuration does not allow creation of non-transactional one here");
    }

    return session;
}

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

/**
 * Get a new Hibernate Session from the given SessionFactory.
 * Will return a new Session even if there already is a pre-bound
 * Session for the given SessionFactory.
 * <p>Within a transaction, this method will create a new Session
 * that shares the transaction's JDBC Connection. More specifically,
 * it will use the same JDBC Connection as the pre-bound Hibernate Session.
 * @param sessionFactory Hibernate SessionFactory to create the session with
 * @param entityInterceptor Hibernate entity interceptor, or {@code null} if none
 * @return the new Session/*from w ww.  j av  a  2  s. c om*/
 */
@SuppressWarnings("deprecation")
public static Session getNewSession(SessionFactory sessionFactory, Interceptor entityInterceptor) {
    Assert.notNull(sessionFactory, "No SessionFactory specified");

    try {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
                .getResource(sessionFactory);
        if (sessionHolder != null && !sessionHolder.isEmpty()) {
            if (entityInterceptor != null) {
                return sessionFactory.openSession(sessionHolder.getAnySession().connection(),
                        entityInterceptor);
            } else {
                return sessionFactory.openSession(sessionHolder.getAnySession().connection());
            }
        } else {
            if (entityInterceptor != null) {
                return sessionFactory.openSession(entityInterceptor);
            } else {
                return sessionFactory.openSession();
            }
        }
    } catch (HibernateException ex) {
        throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
    }
}

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

/**
 * Return whether there is a transactional Hibernate Session for the current thread,
 * that is, a Session bound to the current thread by Spring's transaction facilities.
 * @param sessionFactory Hibernate SessionFactory to check (may be {@code null})
 * @return whether there is a transactional Session for current thread
 *///  w  w w  .j av a2 s  . c o  m
public static boolean hasTransactionalSession(SessionFactory sessionFactory) {
    if (sessionFactory == null) {
        return false;
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    return (sessionHolder != null && !sessionHolder.isEmpty());
}

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

/**
 * Apply the current transaction timeout, if any, to the given
 * Hibernate Criteria object.//from w w  w .  j  a  v  a2s.c  o m
 * @param criteria the Hibernate Criteria object
 * @param sessionFactory Hibernate SessionFactory that the Criteria was created for
 * @see org.hibernate.Criteria#setTimeout
 */
public static void applyTransactionTimeout(Criteria criteria, SessionFactory sessionFactory) {
    Assert.notNull(criteria, "No Criteria object specified");
    if (sessionFactory != null) {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
                .getResource(sessionFactory);
        if (sessionHolder != null && sessionHolder.hasTimeout()) {
            criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
        }
    }
}

From source file:org.springframework.orm.hibernate4.HibernateTemplate.java

/**
 * Prepare the given Query object, applying cache settings and/or
 * a transaction timeout.//from ww  w  .ja  va  2s.co m
 * @param queryObject the Query object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareQuery(Query queryObject) {
    if (isCacheQueries()) {
        queryObject.setCacheable(true);
        if (getQueryCacheRegion() != null) {
            queryObject.setCacheRegion(getQueryCacheRegion());
        }
    }
    if (getFetchSize() > 0) {
        queryObject.setFetchSize(getFetchSize());
    }
    if (getMaxResults() > 0) {
        queryObject.setMaxResults(getMaxResults());
    }

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
            .getResource(getSessionFactory());
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        queryObject.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}