Example usage for org.springframework.jdbc.datasource DataSourceUtils isConnectionTransactional

List of usage examples for org.springframework.jdbc.datasource DataSourceUtils isConnectionTransactional

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DataSourceUtils isConnectionTransactional.

Prototype

public static boolean isConnectionTransactional(Connection con, @Nullable DataSource dataSource) 

Source Link

Document

Determine whether the given JDBC Connection is transactional, that is, bound to the current thread by Spring's transaction facilities.

Usage

From source file:fi.hsl.parkandride.config.JdbcConfiguration.java

@Bean
public Provider<Connection> connectionProvider() {
    return () -> {
        Connection conn = DataSourceUtils.getConnection(dataSource);
        if (!DataSourceUtils.isConnectionTransactional(conn, dataSource)) {
            throw new RuntimeException("Connection should be transactional");
        }//  w w  w  .  jav  a 2  s .co  m
        return conn;
    };
}

From source file:org.mybatis.spring.transaction.SpringManagedTransaction.java

/**
 * Gets a connection from Spring transaction manager and discovers if this
 * {@code Transaction} should manage connection or let it to Spring.
 * <p>//from www  .  jav a  2s.c o m
 * It also reads autocommit setting because when using Spring Transaction MyBatis
 * thinks that autocommit is always false and will always call commit/rollback
 * so we need to no-op that calls.
 */
private void openConnection() throws SQLException {
    this.connection = DataSourceUtils.getConnection(this.dataSource);
    this.autoCommit = this.connection.getAutoCommit();
    this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection,
            this.dataSource);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("JDBC Connection [" + this.connection + "] will"
                + (this.isConnectionTransactional ? " " : " not ") + "be managed by Spring");
    }
}

From source file:com.healthcit.cacure.test.DataSetTestExecutionListener.java

public void beforeTestMethod(TestContext testContext) throws Exception {
    // Determine if a dataset should be loaded, from where, and extract any
    // special configuration.
    Configuration configuration = determineConfiguration(testContext.getTestClass(),
            testContext.getTestMethod());

    if (configuration == null)
        return;/*from w  w  w .ja  v  a2s .  co m*/

    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
            configuration.getUserName(), configuration.getUserPassword()));

    if (configuration.getLocation() == null)
        return;

    configurationCache.put(testContext.getTestMethod(), configuration);

    // Find a single, unambiguous data source.
    DataSource dataSource = lookupDataSource(testContext);

    // Fetch a connection from the data source, using an existing one if we're
    // already participating in a transaction.
    Connection connection = DataSourceUtils.getConnection(dataSource);
    configuration.setConnectionTransactional(DataSourceUtils.isConnectionTransactional(connection, dataSource));

    // Load the data set.
    loadData(configuration, connection);
}

From source file:org.hengdao.utils.SqlSessionUtils.java

/**
 * If a Spring transaction is active it uses {@code DataSourceUtils} to get
 * a Spring managed {@code Connection}, then creates a new
 * {@code SqlSession} with this connection and synchronizes it with the
 * transaction. If there is not an active transaction it gets a connection
 * directly from the {@code DataSource} and creates a {@code SqlSession}
 * with it.//from  w  w  w. j av a  2 s  .co m
 *
 * @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
 */
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator) {

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

    SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.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();
    }

    DataSource dataSource = sessionFactory.getConfiguration().getEnvironment().getDataSource();

    // SqlSessionFactoryBean unwraps TransactionAwareDataSourceProxies but
    // we keep this check for the case that SqlSessionUtils is called from
    // custom code
    boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);
    Connection conn;
    try {
        conn = transactionAware ? dataSource.getConnection() : DataSourceUtils.getConnection(dataSource);
    } catch (SQLException e) {
        throw new CannotGetJdbcConnectionException("Could not get JDBC Connection for SqlSession", e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Creating SqlSession with JDBC Connection [" + conn + "]");
    }

    // Assume either DataSourceTransactionManager or the underlying
    // connection pool already dealt with enabling auto commit.
    // This may not be a good assumption, but the overhead of checking
    // connection.getAutoCommit() again may be expensive (?) in some drivers
    // (see DataSourceTransactionManager.doBegin()). One option would be to
    // only check for auto commit if this function is being called outside
    // of DSTxMgr, but to do that we would need to be able to call
    // ConnectionHolder.isTransactionActive(), which is protected and not
    // visible to this class.
    SqlSession session = sessionFactory.openSession(executorType, conn);

    // Register session holder and bind it to enable synchronization.
    //
    // Note: The DataSource 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 (TransactionSynchronizationManager.isSynchronizationActive()) {
        if (!(sessionFactory.getConfiguration().getEnvironment()
                .getTransactionFactory() instanceof SpringManagedTransactionFactory)
                && DataSourceUtils.isConnectionTransactional(conn, dataSource)) {
            throw new TransientDataAccessResourceException(
                    "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
        }

        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 (logger.isDebugEnabled()) {
            logger.debug("SqlSession [" + session
                    + "] was not registered for synchronization because synchronization is not active");
        }
    }

    return session;
}

From source file:com.taobao.itest.listener.ITestDataSetListener.java

private void buildDataBaseConfig(TestContext testContext, ITestDataSet annotation,
        List<DatasetConfig> datasetConfigs, String location, String dsName, ReplacementDataSet dataSet)
        throws DatabaseUnitException, SQLException {
    DataSource dataSource = (DataSource) SpringContextManager.getApplicationContext().getBean(dsName);
    Connection connection = DataSourceUtils.getConnection(dataSource);

    // build databaseTester start
    IDatabaseConnection Iconn = getDatabaseConnection(dataSource, connection);
    DatabaseConfig config = Iconn.getConfig();

    String dbType = connection.getMetaData().getDatabaseProductName();
    if ("MySQL".equalsIgnoreCase(dbType)) {
        config.setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, new MySqlMetadataHandler());
    } else if ("Oracle".equalsIgnoreCase(dbType)) {
        config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new Oracle10DataTypeFactory());
    }//from w w w. j  a  v  a2  s  . c  om

    Date dbNow = getDbCurrentTime(connection, dbType);
    addSysdateReplacement(dataSet, dbNow);
    addTimeStampReplacement(dataSet, dbNow);

    IDatabaseTester databaseTester = new DefaultDatabaseTester(Iconn);
    databaseTester.setDataSet(dataSet);
    String setUp = annotation.setupOperation();
    DatabaseOperation setUpOperation = "REFRESH".equals(setUp) ? new RefreshOperation()
            : (DatabaseOperation) databaseOperations.asObject(setUp);
    databaseTester.setSetUpOperation(setUpOperation);

    String teardown = annotation.teardownOperation();
    DatabaseOperation teardownOperation = "DELETE".equals(teardown) ? new DeleteOperation()
            : (DatabaseOperation) databaseOperations.asObject(teardown);
    databaseTester.setTearDownOperation(teardownOperation);
    // build databaseTester end

    boolean transactional = DataSourceUtils.isConnectionTransactional(connection, dataSource);
    DatasetConfig datasetConfig = new DatasetConfig(databaseTester, transactional).location(location)
            .dsName(dsName).setupOperation(annotation.setupOperation())
            .teardownOperation(annotation.teardownOperation());

    datasetConfigs.add(datasetConfig);
}