Example usage for java.sql Connection TRANSACTION_READ_COMMITTED

List of usage examples for java.sql Connection TRANSACTION_READ_COMMITTED

Introduction

In this page you can find the example usage for java.sql Connection TRANSACTION_READ_COMMITTED.

Prototype

int TRANSACTION_READ_COMMITTED

To view the source code for java.sql Connection TRANSACTION_READ_COMMITTED.

Click Source Link

Document

A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.

Usage

From source file:org.cloudgraph.rdb.service.RDBGraphService.java

public int count(Query query) {
    if (query == null)
        throw new IllegalArgumentException("expected non-null 'query' argument");
    validate(query);//from ww  w. j  a  va  2  s  .c o m
    if (log.isDebugEnabled()) {
        log(query);
    }
    Connection con = null;
    try {
        if (log.isDebugEnabled())
            log.debug("getting connection");
        con = ProviderManager.instance().getConnection();
        if (con.getAutoCommit()) {
            if (log.isDebugEnabled())
                log.debug("turning off connection autocommit for count query");
            con.setAutoCommit(false);
        }
        RDBMSVendorName vendor = PlasmaRuntime.getInstance()
                .getRDBMSProviderVendor(DataAccessProviderName.JDBC);
        switch (vendor) {
        case ORACLE:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        case MYSQL:
            con.setTransactionIsolation(Connection.TRANSACTION_NONE); // Oracle
            // does
            // not
            // support
            break;
        default:
        }
        // TODO: make transaction isolation configurable
        if (log.isDebugEnabled())
            log.debug(
                    "using transaction isolation level " + con.getTransactionIsolation() + " for count query");
    } catch (SQLException e2) {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        throw new DataAccessException(e2);
    }
    GraphQuery dispatcher = new GraphQuery(con);
    try {
        return dispatcher.count(query);
    } finally {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
    }
}

From source file:com.amazon.carbonado.repo.jdbc.JDBCRepository.java

static IsolationLevel mapIsolationLevelFromJdbc(int jdbcLevel) {
    switch (jdbcLevel) {
    case Connection.TRANSACTION_NONE:
    default:/*from w  w w . j a va 2 s.  c o m*/
        return IsolationLevel.NONE;
    case Connection.TRANSACTION_READ_UNCOMMITTED:
        return IsolationLevel.READ_UNCOMMITTED;
    case Connection.TRANSACTION_READ_COMMITTED:
        return IsolationLevel.READ_COMMITTED;
    case Connection.TRANSACTION_REPEATABLE_READ:
        return IsolationLevel.REPEATABLE_READ;
    case Connection.TRANSACTION_SERIALIZABLE:
        return IsolationLevel.SERIALIZABLE;
    }
}

From source file:org.artifactory.storage.db.itest.spring.DbTestConfigFactory.java

/**
 * @return Auto-commit datasource for the unique ids generator.
 * @see org.artifactory.storage.db.spring.DbConfigFactory#createUniqueIdsDataSource()
 */// w  w  w.j  ava2  s  .  com
@Bean(name = "uniqueIdsDataSource")
public PoolingDataSource createUniqueIdsDataSource() {
    StorageProperties storageProperties = beanFactory.getBean("storageProperties", StorageProperties.class);

    GenericObjectPool.Config poolConfig = new GenericObjectPool.Config();
    poolConfig.maxActive = 1;
    poolConfig.maxIdle = 1;
    ObjectPool connectionPool = new GenericObjectPool(null, poolConfig);

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
            storageProperties.getConnectionUrl(), storageProperties.getUsername(),
            storageProperties.getPassword());

    // default auto commit true!
    PoolableConnectionFactory pcf = new ArtifactoryPoolableConnectionFactory(connectionFactory, connectionPool,
            null, null, false, true);
    pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return new PoolingDataSource(connectionPool);
}

From source file:org.sakaiproject.tomcat.jdbc.pool.SakaiBasicDataSource.java

/**
 * Set the default transaction isolation level from a string value, based on the settings and values in java.sql.Connection
 * /*  w w  w .  j a  va  2 s.com*/
 * @param defaultTransactionIsolation
 */
public void setDefaultTransactionIsolationString(String defaultTransactionIsolation) {
    if ((defaultTransactionIsolation == null) || (defaultTransactionIsolation.trim().length() == 0)) {
        setDefaultTransactionIsolation(DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_NONE")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_READ_UNCOMMITTED")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_READ_COMMITTED")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_REPEATABLE_READ")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_SERIALIZABLE")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    } else {
        setDefaultTransactionIsolation(DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION);
        M_log.warn("invalid transaction isolation level: " + defaultTransactionIsolation);
    }
}

From source file:org.apache.sqoop.connector.jdbc.oracle.util.OracleConnectionFactory.java

public static void initializeOracleConnection(Connection connection, ConnectionConfig config)
        throws SQLException {

    connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    connection.setAutoCommit(false);//from ww w  . j a v  a 2  s.  c  om

    OracleQueries.setConnectionTimeZone(connection, config.timeZone);

    setSessionClientInfo(connection, config);

    OracleQueries.setJdbcFetchSize(connection, config.fetchSize);

    executeOraOopSessionInitializationStatements(connection, config.initializationStatements);
}

From source file:com.zaxxer.hikari.benchmark.BenchBase.java

protected void setupTomcat() {
    PoolProperties props = new PoolProperties();
    props.setUrl(jdbcURL);/*  w  ww.  ja  v a  2  s .c om*/
    props.setDriverClassName(dbDriver);
    props.setUsername("sa");
    props.setPassword("");
    props.setInitialSize(MIN_POOL_SIZE);
    props.setMinIdle(MIN_POOL_SIZE);
    props.setMaxIdle(maxPoolSize);
    props.setMaxActive(maxPoolSize);
    props.setMaxWait(8000);
    props.setDefaultAutoCommit(false);
    props.setRollbackOnReturn(true);
    props.setMinEvictableIdleTimeMillis((int) TimeUnit.MINUTES.toMillis(30));
    props.setTestOnBorrow(true);
    props.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    props.setValidationQuery("VALUES 1");
    props.setJdbcInterceptors("ConnectionState");

    DS = new org.apache.tomcat.jdbc.pool.DataSource(props);
}

From source file:org.wso2.carbon.registry.core.jdbc.dataaccess.JDBCTransactionManager.java

public void beginTransaction() throws RegistryException {
    if (dataAccessManager.getDatabaseTransaction().getNestedDepth() != 0) {
        if (log.isTraceEnabled()) {
            log.trace("The transaction was not started, because it is called within a "
                    + "transaction, nested depth: "
                    + dataAccessManager.getDatabaseTransaction().getNestedDepth() + ".");
        }/*  www .  ja  va2 s  .c om*/
        dataAccessManager.getDatabaseTransaction().incNestedDepth();
        if (JDBCDatabaseTransaction.getConnection() != null) {
            return;
        } else {
            // If we get here, there has been some issue related to connection failure.
            // There is no point in using the connection that is already existing on this
            // thread. We need to start using a new one.
            while (dataAccessManager.getDatabaseTransaction().getNestedDepth() > 0) {
                dataAccessManager.getDatabaseTransaction().decNestedDepth();
            }
            while (dataAccessManager.getDatabaseTransaction().getNestedDepth() < 0) {
                dataAccessManager.getDatabaseTransaction().incNestedDepth();
            }
        }
    }

    Connection conn;
    try {
        if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
            String msg = "Failed to begin transaction. Invalid data access manager.";
            log.error(msg);
            throw new RegistryException(msg);
        }
        DataSource dataSource = ((JDBCDataAccessManager) dataAccessManager).getDataSource();
        conn = dataSource.getConnection();

        // If a managed connection already exists, use that instead of a new connection.
        JDBCDatabaseTransaction.ManagedRegistryConnection temp = JDBCDatabaseTransaction
                .getManagedRegistryConnection(conn);
        if (temp != null) {
            conn.close();
            conn = temp;
        }
        if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        conn.setAutoCommit(false);
        dataAccessManager.getDatabaseTransaction().incNestedDepth();
    } catch (SQLException e) {
        String msg = "Failed to start new registry transaction.";
        log.error(msg, e);
        throw new RegistryException(msg, e);
    }

    JDBCDatabaseTransaction.setConnection(conn);
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCPathCache.java

/**
 * Method to add resource path entry to the database.
 *
 * @param path         the path to add.//from www.  ja  va2  s .co  m
 * @param parentPathId the parent path's id.
 *
 * @return the path's id.
 * @throws RegistryException if the data access manager was invalid.
 * @throws SQLException      if an error occurs while adding the entry.
 */
public int addEntry(String path, int parentPathId) throws SQLException, RegistryException {
    ResultSet results = null;
    PreparedStatement ps = null;
    PreparedStatement ps1 = null;
    DataAccessManager dataAccessManager;
    if (CurrentSession.getUserRegistry() != null
            && CurrentSession.getUserRegistry().getRegistryContext() != null) {
        dataAccessManager = CurrentSession.getUserRegistry().getRegistryContext().getDataAccessManager();
    } else {
        // TODO: This code block doesn't seem to get hit. Remove if unused.
        dataAccessManager = RegistryContext.getBaseInstance().getDataAccessManager();
    }
    if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
        String msg = "Failed to add path entry. Invalid data access manager.";
        log.error(msg);
        throw new RegistryException(msg);
    }
    DataSource dataSource = ((JDBCDataAccessManager) dataAccessManager).getDataSource();
    Connection conn = dataSource.getConnection();
    if (conn != null) {
        if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        conn.setAutoCommit(false);
    } else {
        log.error("Unable to acquire connection to database.");
        return -1;
    }
    boolean success = false;
    int pathId = 0;

    try {
        String sql = "INSERT INTO REG_PATH(REG_PATH_VALUE, REG_PATH_PARENT_ID, REG_TENANT_ID) "
                + "VALUES (?, ?, ?)";
        String sql1 = "SELECT MAX(REG_PATH_ID) FROM REG_PATH";
        String dbProductName = conn.getMetaData().getDatabaseProductName();
        boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName);
        if (returnsGeneratedKeys) {
            ps = conn.prepareStatement(sql,
                    new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "REG_PATH_ID") });
        } else {
            ps = conn.prepareStatement(sql);
        }
        ps.setString(1, path);
        ps.setInt(2, parentPathId);
        ps.setInt(3, CurrentSession.getTenantId());
        if (returnsGeneratedKeys) {
            ps.executeUpdate();
            results = ps.getGeneratedKeys();
        } else {
            synchronized (ADD_ENTRY_LOCK) {
                ps.executeUpdate();
                ps1 = conn.prepareStatement(sql1);
                results = ps1.executeQuery();
            }
        }
        if (results.next()) {
            pathId = results.getInt(1);
            if (pathId > 0) {
                success = true;
                return pathId;
            }
        }
    } catch (SQLException e) {
        // we have to be expecting an exception with the duplicate value for the path value
        // which can be further checked from here..
        String msg = "Failed to insert resource to " + path + ". " + e.getMessage();
        log.error(msg, e);
        throw e;
    } finally {
        if (success) {
            try {
                conn.commit();
                RegistryCacheEntry e = new RegistryCacheEntry(pathId);
                String connectionId = null;
                if (conn.getMetaData() != null) {
                    connectionId = RegistryUtils.getConnectionId(conn);
                }
                RegistryCacheKey key = RegistryUtils.buildRegistryCacheKey(connectionId,
                        CurrentSession.getTenantId(), path);
                getCache().put(key, e);

            } catch (SQLException e) {
                String msg = "Failed to commit transaction. Inserting " + path + ". " + e.getMessage();
                log.error(msg, e);
            } finally {
                try {
                    try {
                        if (results != null) {
                            results.close();
                        }
                    } finally {
                        try {
                            if (ps1 != null) {
                                ps1.close();
                            }
                        } finally {
                            try {
                                if (ps != null) {
                                    ps.close();
                                }
                            } finally {
                                conn.close();
                            }
                        }
                    }
                } catch (SQLException e) {
                    String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR + e.getMessage();
                    log.error(msg, e);
                }
            }
        } else {
            try {
                conn.rollback();

            } catch (SQLException e) {
                String msg = "Failed to rollback transaction. Inserting " + path + ". " + e.getMessage();
                log.error(msg, e);
            } finally {
                try {
                    try {
                        if (results != null) {
                            results.close();
                        }
                    } finally {
                        try {
                            if (ps != null) {
                                ps.close();
                            }
                        } finally {
                            if (conn != null) {
                                conn.close();
                            }
                        }
                    }
                } catch (SQLException e) {
                    String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR + e.getMessage();
                    log.error(msg, e);
                }
            }
        }
    }
    return -1;
}

From source file:org.wso2.carbon.repository.core.jdbc.dataaccess.JDBCTransactionManager.java

public void beginTransaction() throws RepositoryException {
    if (dataAccessManager.getDatabaseTransaction().getNestedDepth() != 0) {
        if (log.isTraceEnabled()) {
            log.trace(/*from  w w w  .  j  ava2s.  co m*/
                    "The transaction was not started, because it is called within a transaction, nested depth: "
                            + dataAccessManager.getDatabaseTransaction().getNestedDepth() + ".");
        }

        dataAccessManager.getDatabaseTransaction().incNestedDepth();

        if (JDBCDatabaseTransaction.getConnection() != null) {
            return;
        } else {
            // If we get here, there has been some issue related to connection failure.
            // There is no point in using the connection that is already existing on this
            // thread. We need to start using a new one.
            while (dataAccessManager.getDatabaseTransaction().getNestedDepth() > 0) {
                dataAccessManager.getDatabaseTransaction().decNestedDepth();
            }

            while (dataAccessManager.getDatabaseTransaction().getNestedDepth() < 0) {
                dataAccessManager.getDatabaseTransaction().incNestedDepth();
            }
        }
    }

    Connection conn;

    try {
        if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
            String msg = "Failed to begin transaction. Invalid data access manager.";
            log.error(msg);
            throw new RepositoryDBException(msg);
        }

        DataSource dataSource = ((JDBCDataAccessManager) dataAccessManager).getDataSource();
        conn = dataSource.getConnection();

        // If a managed connection already exists, use that instead of a new connection.
        JDBCDatabaseTransaction.ManagedRegistryConnection temp = JDBCDatabaseTransaction
                .getManagedRegistryConnection(conn);

        if (temp != null) {
            conn.close();
            conn = temp;
        }

        if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }

        conn.setAutoCommit(false);
        dataAccessManager.getDatabaseTransaction().incNestedDepth();
    } catch (SQLException e) {
        String msg = "Failed to start new registry transaction.";
        log.error(msg, e);
        throw new RepositoryDBException(msg, e);
    }

    JDBCDatabaseTransaction.setConnection(conn);
}

From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCPathCache.java

/**
 * Method to add resource path entry to the database.
 *
 * @param path         the path to add./*from w w w  . j  a  va 2  s .  co m*/
 * @param parentPathId the parent path's id.
 *
 * @return the path's id.
 * @throws RepositoryException if the data access manager was invalid.
 * @throws SQLException      if an error occurs while adding the entry.
 */
public int addEntry(String path, int parentPathId) throws SQLException, RepositoryException {
    ResultSet results = null;
    PreparedStatement ps = null;
    PreparedStatement ps1 = null;
    DataAccessManager dataAccessManager;

    if (CurrentContext.getRespository() != null
            && InternalUtils.getRepositoryContext(CurrentContext.getRespository()) != null) {
        dataAccessManager = InternalUtils.getRepositoryContext(CurrentContext.getRespository())
                .getDataAccessManager();
    } else {
        dataAccessManager = RepositoryContext.getBaseInstance().getDataAccessManager();
    }

    if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
        String msg = "Failed to add path entry. Invalid data access manager.";
        log.error(msg);
        throw new RepositoryServerException(msg);
    }

    DataSource dataSource = ((JDBCDataAccessManager) dataAccessManager).getDataSource();
    Connection conn = dataSource.getConnection();

    if (conn != null) {
        if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        conn.setAutoCommit(false);
    } else {
        log.error("Unable to acquire connection to database.");
        return -1;
    }

    boolean success = false;
    int pathId = 0;

    try {
        String sql = "INSERT INTO REG_PATH(REG_PATH_VALUE, REG_PATH_PARENT_ID, REG_TENANT_ID) VALUES (?, ?, ?)";
        String sql1 = "SELECT MAX(REG_PATH_ID) FROM REG_PATH";

        String dbProductName = conn.getMetaData().getDatabaseProductName();
        boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName);

        if (returnsGeneratedKeys) {
            ps = conn.prepareStatement(sql,
                    new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "REG_PATH_ID") });
        } else {
            ps = conn.prepareStatement(sql);
        }

        ps.setString(1, path);
        ps.setInt(2, parentPathId);
        ps.setInt(3, CurrentContext.getTenantId());

        if (returnsGeneratedKeys) {
            ps.executeUpdate();
            results = ps.getGeneratedKeys();
        } else {
            synchronized (ADD_ENTRY_LOCK) {
                ps.executeUpdate();
                ps1 = conn.prepareStatement(sql1);
                results = ps1.executeQuery();
            }
        }

        if (results.next()) {
            pathId = results.getInt(1);
            if (pathId > 0) {
                success = true;
                return pathId;
            }
        }
    } catch (SQLException e) {
        // we have to be expecting an exception with the duplicate value for the path value
        // which can be further checked from here..
        String msg = "Failed to insert resource to " + path + ". " + e.getMessage();
        log.error(msg, e);
        throw e;
    } finally {
        if (success) {
            try {
                conn.commit();
                RepositoryCacheEntry e = new RepositoryCacheEntry(pathId);
                String connectionId = null;

                if (conn.getMetaData() != null) {
                    connectionId = InternalUtils.getConnectionId(conn);
                }

                RepositoryCacheKey key = InternalUtils.buildRegistryCacheKey(connectionId,
                        CurrentContext.getTenantId(), path);
                getCache().put(key, e);
            } catch (SQLException e) {
                String msg = "Failed to commit transaction. Inserting " + path + ". " + e.getMessage();
                log.error(msg, e);
            } finally {
                try {
                    try {
                        if (results != null) {
                            results.close();
                        }
                    } finally {
                        try {
                            if (ps1 != null) {
                                ps1.close();
                            }
                        } finally {
                            try {
                                if (ps != null) {
                                    ps.close();
                                }
                            } finally {
                                conn.close();
                            }
                        }
                    }
                } catch (SQLException e) {
                    String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR + e.getMessage();
                    log.error(msg, e);
                }
            }
        } else {
            try {
                conn.rollback();

            } catch (SQLException e) {
                String msg = "Failed to rollback transaction. Inserting " + path + ". " + e.getMessage();
                log.error(msg, e);
            } finally {
                try {
                    try {
                        if (results != null) {
                            results.close();
                        }
                    } finally {
                        try {
                            if (ps != null) {
                                ps.close();
                            }
                        } finally {
                            if (conn != null) {
                                conn.close();
                            }
                        }
                    }
                } catch (SQLException e) {
                    String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR + e.getMessage();
                    log.error(msg, e);
                }
            }
        }
    }
    return -1;
}