Example usage for org.apache.ibatis.mapping Environment getTransactionFactory

List of usage examples for org.apache.ibatis.mapping Environment getTransactionFactory

Introduction

In this page you can find the example usage for org.apache.ibatis.mapping Environment getTransactionFactory.

Prototype

public TransactionFactory getTransactionFactory() 

Source Link

Usage

From source file:com.raycloud.cobarclient.mybatis.spring.SqlSessionUtils.java

License:Apache License

/**
 * Gets an SqlSession from Spring Transaction Manager or creates a new one if needed.
 * Tries to get a SqlSession out of current transaction. If there is not any, it creates a new one.
 * Then, it synchronizes the SqlSession with the transaction if Spring TX is active and
 * <code>SpringManagedTransactionFactory</code> is configured as a transaction manager.
 *
 * @param sessionFactory      a MyBatis {@code SqlSessionFactory} to create new sessions
 * @param executorType        The executor type of the SqlSession to create
 * @param exceptionTranslator Optional. Translates SqlSession.commit() exceptions to Spring exceptions.
 * @throws TransientDataAccessResourceException if a transaction is active and the
 *                                              {@code SqlSessionFactory} is not using a {@code SpringManagedTransactionFactory}
 * @see SpringManagedTransactionFactory//  www .ja  v a 2 s  . c  om
 */
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator) {

    notNull(sessionFactory, "No SqlSessionFactory specified");
    notNull(executorType, "No ExecutorType specified");

    SqlSessionHolder holder = (SqlSessionHolder) getResource(sessionFactory);

    if (holder != null && holder.isSynchronizedWithTransaction()) {
        if (holder.getExecutorType() != executorType) {
            throw new TransientDataAccessResourceException(
                    "Cannot change the ExecutorType when there is an existing transaction");
        }

        holder.requested();

        if (logger.isDebugEnabled()) {
            logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
        }

        return holder.getSqlSession();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Creating a new SqlSession");
    }

    SqlSession session = sessionFactory.openSession(executorType);

    // 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.
    if (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);
            bindResource(sessionFactory, holder);
            registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
            holder.setSynchronizedWithTransaction(true);
            holder.requested();
        } else {
            if (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");
        }
    }

    return session;
}

From source file:com.raycloud.cobarclient.mybatis.spring.SqlSessionUtils.java

License:Apache License

/**
 * Environment?//from   w w  w. j  av a 2  s.  co  m
 *
 * @param sessionFactory
 * @param executorType
 * @param exceptionTranslator
 * @param environment
 * @return
 */
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator, Environment environment, SqlSessionHolder holder) {

    notNull(sessionFactory, "No SqlSessionFactory specified");
    notNull(executorType, "No ExecutorType specified");

    holder = (holder == null) ? (SqlSessionHolder) getResource(sessionFactory) : holder;

    if (holder != null && holder.isSynchronizedWithTransaction()) {
        if (holder.getExecutorType() != executorType) {
            throw new TransientDataAccessResourceException(
                    "Cannot change the ExecutorType when there is an existing transaction");
        }

        holder.requested();

        if (logger.isDebugEnabled()) {
            logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
        }

        return holder.getSqlSession();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Creating a new SqlSession");
    }

    SqlSession session = /**sessionFactory.openSession(executorType);**/
            openSession(environment, sessionFactory, executorType);

    // 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.
    if (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);
            bindResource(sessionFactory, holder);
            registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
            holder.setSynchronizedWithTransaction(true);
            holder.requested();
        } else {
            if (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");
        }
    }

    return session;
}

From source file:com.raycloud.cobarclient.mybatis.spring.SqlSessionUtils.java

License:Apache License

/**
 * Environment?/*from w ww  .j  a  v a  2 s .  com*/
 *
 * @param environment
 * @param sessionFactory
 * @param executorType
 * @return
 */
private static SqlSession openSession(Environment environment, SqlSessionFactory sessionFactory,
        ExecutorType executorType) {
    Transaction tx = null;
    try {
        final TransactionFactory transactionFactory = environment.getTransactionFactory();
        tx = transactionFactory.newTransaction(environment.getDataSource(), null, false);
        final Executor executor = sessionFactory.getConfiguration().newExecutor(tx, executorType);
        return new DefaultSqlSession(sessionFactory.getConfiguration(), executor, false);
    } catch (Exception e) {
        closeTransaction(tx); // may have fetched a connection so lets call close()
        throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
        ErrorContext.instance().reset();
    }
}

From source file:org.activiti.MultiTenantSqlSessionFactory.java

License:Apache License

private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
    if (environment == null || environment.getTransactionFactory() == null) {
        return new ManagedTransactionFactory();
    }/*  w w w  .j  a  v  a2 s .  c o m*/
    return environment.getTransactionFactory();
}

From source file:org.mybatis.guice.environment.EnvironmentProviderTest.java

License:Apache License

@Test
public void get() {
    Environment environment = environmentProvider.get();
    assertEquals(id, environment.getId());
    assertEquals(dataSource, environment.getDataSource());
    assertEquals(transactionFactory, environment.getTransactionFactory());
}

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

License:Apache License

/**
 * 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  ww. jav  a2s .c o  m*/
 * @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");
        }
    }
}