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.spring.data.gemfire.app.dao.provider.JdbcUserDao.java

public Iterable<User> batchInsert(final Iterable<User> users) {
    Connection connection = createConnectionBuilder().setAutoCommit(false)
            .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED).build();

    try {//from www  .  j a v  a2 s.  c o  m
        PreparedStatement statement = connection.prepareStatement(INSERT_USER_SQL);

        for (User user : users) {
            prepareInsert(statement, user);
            statement.executeUpdate();
        }

        connection.commit();

        return users;
    } catch (SQLException e) {
        rollback(connection);
        throw createDataAccessException(String.format("Failed to save the Collection of Users (%1$s)!", users),
                e);
    }
}

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

public List<DataGraph[]> find(Query[] queries) {
    if (queries == null)
        throw new IllegalArgumentException("expected non-null 'queries' argument");
    Connection con = null;/*from ww  w .  j a  va2 s.c o m*/
    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 multi graph query");
            con.setAutoCommit(false);
        }

        // TODO: make transaction isolation configurable
        RDBMSVendorName vendor = PlasmaRuntime.getInstance()
                .getRDBMSProviderVendor(DataAccessProviderName.JDBC);
        switch (vendor) {
        case ORACLE:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        case MYSQL:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        default:
        }
        if (log.isDebugEnabled())
            log.debug("using transaction isolation level " + con.getTransactionIsolation()
                    + " for multi graph 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);
    List<DataGraph[]> list = new ArrayList<DataGraph[]>();
    Timestamp snapshotDate = new Timestamp((new Date()).getTime());
    try {
        for (int i = 0; i < queries.length; i++) {
            validate(queries[i]);
            if (log.isDebugEnabled()) {
                log(queries[i]);
            }
            DataGraph[] results = dispatcher.find(queries[i], snapshotDate);
            list.add(results);
        }
        return list;
    } finally {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                if (con != null)
                    con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
    }
}

From source file:com.cloudera.sqoop.manager.OracleManager.java

/**
 * Create a connection to the database; usually used only from within
 * getConnection(), which enforces a singleton guarantee around the
 * Connection object.//from   w w w  .  ja  v  a 2s .  c  o m
 *
 * Oracle-specific driver uses READ_COMMITTED which is the weakest
 * semantics Oracle supports.
 */
protected Connection makeConnection() throws SQLException {

    Connection connection;
    String driverClass = getDriverClass();

    try {
        Class.forName(driverClass);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException("Could not load db driver class: " + driverClass);
    }

    String username = options.getUsername();
    String password = options.getPassword();
    String connectStr = options.getConnectString();

    connection = CACHE.getConnection(connectStr, username);
    if (null == connection) {
        // Couldn't pull one from the cache. Get a new one.
        LOG.debug("Creating a new connection for " + connectStr + "/" + username);
        if (null == username) {
            connection = DriverManager.getConnection(connectStr);
        } else {
            connection = DriverManager.getConnection(connectStr, username, password);
        }
    }

    // We only use this for metadata queries. Loosest semantics are okay.
    connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    // Setting session time zone
    setSessionTimeZone(connection);

    return connection;
}

From source file:org.wso2.carbon.datasource.ui.DataSourceManagementHelper.java

public static String toStringIsolation(int isolation) {
    switch (isolation) {
    case Connection.TRANSACTION_NONE: {
        return "TRANSACTION_NONE";
    }/*from   w ww.  j  a v  a2 s .  c  om*/
    case Connection.TRANSACTION_READ_COMMITTED: {
        return "TRANSACTION_READ_COMMITTED";
    }
    case Connection.TRANSACTION_READ_UNCOMMITTED: {
        return "TRANSACTION_READ_UNCOMMITTED";
    }
    case Connection.TRANSACTION_REPEATABLE_READ: {
        return "TRANSACTION_REPEATABLE_READ";
    }
    case Connection.TRANSACTION_SERIALIZABLE: {
        return "TRANSACTION_SERIALIZABLE";
    }
    default: {
        return "TRANSACTION_UNKNOWN";
    }
    }
}

From source file:com.feedzai.commons.sql.abstraction.engine.configuration.PdbProperties.java

/**
 * Gets the isolation level./*from ww  w  . j a va  2  s.co  m*/
 *
 * @return The isolation level.
 */
public int getIsolationLevel() {
    final Optional<IsolationLevel> e = Enums.getIfPresent(IsolationLevel.class,
            getProperty(ISOLATION_LEVEL).toUpperCase());

    if (!e.isPresent()) {
        throw new DatabaseEngineRuntimeException(ISOLATION_LEVEL + " must be set and be one of the following: "
                + EnumSet.allOf(IsolationLevel.class));
    }

    switch (e.get()) {
    case READ_UNCOMMITTED:
        return Connection.TRANSACTION_READ_UNCOMMITTED;
    case READ_COMMITTED:
        return Connection.TRANSACTION_READ_COMMITTED;
    case REPEATABLE_READ:
        return Connection.TRANSACTION_REPEATABLE_READ;
    case SERIALIZABLE:
        return Connection.TRANSACTION_SERIALIZABLE;
    default:
        // Never happens.
        throw new DatabaseEngineRuntimeException("New isolation level?!" + e.get());
    }
}

From source file:org.wso2.carbon.datasource.core.utils.RDBMSDataSourceUtils.java

public static PoolConfiguration createPoolConfiguration(RDBMSConfiguration config) throws DataSourceException {
    PoolProperties props = new PoolProperties();
    props.setUrl(config.getUrl());/*from  w  ww .  jav a2 s.c  o m*/
    if (config.isDefaultAutoCommit() != null) {
        props.setDefaultAutoCommit(config.isDefaultAutoCommit());
    }
    if (config.isDefaultReadOnly() != null) {
        props.setDefaultReadOnly(config.isDefaultReadOnly());
    }
    String isolationLevelString = config.getDefaultTransactionIsolation();
    if (isolationLevelString != null) {
        if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.NONE.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        } else if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.READ_UNCOMMITTED.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.READ_COMMITTED.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.REPEATABLE_READ.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.SERIALIZABLE.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        }
    }
    props.setDefaultCatalog(config.getDefaultCatalog());
    props.setDriverClassName(config.getDriverClassName());
    props.setUsername(config.getUsername());
    props.setPassword(config.getPassword());
    if (config.getMaxActive() != null) {
        props.setMaxActive(config.getMaxActive());
    }
    if (config.getMaxIdle() != null) {
        props.setMaxIdle(config.getMaxIdle());
    }
    if (config.getMinIdle() != null) {
        props.setMinIdle(config.getMinIdle());
    }
    if (config.getInitialSize() != null) {
        props.setInitialSize(config.getInitialSize());
    }
    if (config.getMaxWait() != null) {
        props.setMaxWait(config.getMaxWait());
    }
    if (config.isTestOnBorrow() != null) {
        props.setTestOnBorrow(config.isTestOnBorrow());
    }
    if (config.isTestOnReturn() != null) {
        props.setTestOnReturn(config.isTestOnReturn());
    }
    if (config.isTestWhileIdle() != null) {
        props.setTestWhileIdle(config.isTestWhileIdle());
    }
    props.setValidationQuery(config.getValidationQuery());
    props.setValidatorClassName(config.getValidatorClassName());
    if (config.getTimeBetweenEvictionRunsMillis() != null) {
        props.setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis());
    }
    if (config.getNumTestsPerEvictionRun() != null) {
        props.setNumTestsPerEvictionRun(config.getNumTestsPerEvictionRun());
    }
    if (config.getMinEvictableIdleTimeMillis() != null) {
        props.setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis());
    }
    if (config.isAccessToUnderlyingConnectionAllowed() != null) {
        props.setAccessToUnderlyingConnectionAllowed(config.isAccessToUnderlyingConnectionAllowed());
    }
    if (config.isRemoveAbandoned() != null) {
        props.setRemoveAbandoned(config.isRemoveAbandoned());
    }
    if (config.getRemoveAbandonedTimeout() != null) {
        props.setRemoveAbandonedTimeout(config.getRemoveAbandonedTimeout());
    }
    if (config.isLogAbandoned() != null) {
        props.setLogAbandoned(config.isLogAbandoned());
    }
    props.setConnectionProperties(config.getConnectionProperties());
    props.setInitSQL(config.getInitSQL());
    props.setJdbcInterceptors(config.getJdbcInterceptors());
    if (config.getValidationInterval() != null) {
        props.setValidationInterval(config.getValidationInterval());
    }
    if (config.isJmxEnabled() != null) {
        props.setJmxEnabled(config.isJmxEnabled());
    }
    if (config.isFairQueue() != null) {
        props.setFairQueue(config.isFairQueue());
    }
    if (config.getAbandonWhenPercentageFull() != null) {
        props.setAbandonWhenPercentageFull(config.getAbandonWhenPercentageFull());
    }
    if (config.getMaxAge() != null) {
        props.setMaxAge(config.getMaxAge());
    }
    if (config.isUseEquals() != null) {
        props.setUseEquals(config.isUseEquals());
    }
    if (config.getSuspectTimeout() != null) {
        props.setSuspectTimeout(config.getSuspectTimeout());
    }
    if (config.isAlternateUsernameAllowed() != null) {
        props.setAlternateUsernameAllowed(config.isAlternateUsernameAllowed());
    }
    if (config.getDataSourceClassName() != null) {
        handleExternalDataSource(props, config);
    }
    return props;
}

From source file:org.apache.hadoop.hive.metastore.txn.CompactionTxnHandler.java

/**
 * Find entries in the queue that are ready to
 * be cleaned./*from w  ww  . jav a  2s.co  m*/
 * @return information on the entry in the queue.
 */
public List<CompactionInfo> findReadyToClean() throws MetaException {
    Connection dbConn = null;
    List<CompactionInfo> rc = new ArrayList<CompactionInfo>();

    Statement stmt = null;
    try {
        try {
            dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
            stmt = dbConn.createStatement();
            String s = "select cq_id, cq_database, cq_table, cq_partition, "
                    + "cq_type, cq_run_as from COMPACTION_QUEUE where cq_state = '" + READY_FOR_CLEANING + "'";
            LOG.debug("Going to execute query <" + s + ">");
            ResultSet rs = stmt.executeQuery(s);
            while (rs.next()) {
                CompactionInfo info = new CompactionInfo();
                info.id = rs.getLong(1);
                info.dbname = rs.getString(2);
                info.tableName = rs.getString(3);
                info.partName = rs.getString(4);
                switch (rs.getString(5).charAt(0)) {
                case MAJOR_TYPE:
                    info.type = CompactionType.MAJOR;
                    break;
                case MINOR_TYPE:
                    info.type = CompactionType.MINOR;
                    break;
                default:
                    throw new MetaException("Unexpected compaction type " + rs.getString(5));
                }
                info.runAs = rs.getString(6);
                rc.add(info);
            }
            LOG.debug("Going to rollback");
            dbConn.rollback();
            return rc;
        } catch (SQLException e) {
            LOG.error("Unable to select next element for cleaning, " + e.getMessage());
            LOG.debug("Going to rollback");
            rollbackDBConn(dbConn);
            checkRetryable(dbConn, e, "findReadyToClean");
            throw new MetaException(
                    "Unable to connect to transaction database " + StringUtils.stringifyException(e));
        } finally {
            closeDbConn(dbConn);
            closeStmt(stmt);
        }
    } catch (RetryException e) {
        return findReadyToClean();
    }
}

From source file:com.zimbra.cs.db.DbPool.java

public static DbConnection getConnection(Mailbox mbox) throws ServiceException {
    if (!isInitialized()) {
        throw ServiceException.FAILURE("Database connection pool not initialized.", null);
    }/*from w w  w.  j a v  a2  s  .c o m*/
    Integer mboxId = mbox != null ? mbox.getId() : -1; //-1 == zimbra db and/or initialization where mbox isn't known yet
    try {
        Db.getInstance().preOpen(mboxId);
        long start = ZimbraPerf.STOPWATCH_DB_CONN.start();

        // If the connection pool is overutilized, warn about potential leaks
        PoolingDataSource pool = getPool();
        checkPoolUsage();

        Connection dbconn = null;
        DbConnection conn = null;
        try {
            dbconn = pool.getConnection();

            if (dbconn.getAutoCommit() != false)
                dbconn.setAutoCommit(false);

            // We want READ COMMITTED transaction isolation level for duplicate
            // handling code in BucketBlobStore.newBlobInfo().
            if (Db.supports(Db.Capability.READ_COMMITTED_ISOLATION))
                dbconn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

            conn = new DbConnection(dbconn, mboxId);
            Db.getInstance().postOpen(conn);
        } catch (SQLException e) {
            try {
                if (dbconn != null && !dbconn.isClosed())
                    dbconn.close();
            } catch (SQLException e2) {
                ZimbraLog.sqltrace.warn("DB connection close caught exception", e);
            }
            throw ServiceException.FAILURE("getting database connection", e);
        }

        // If we're debugging, update the counter with the current stack trace
        if (ZimbraLog.dbconn.isDebugEnabled()) {
            Throwable t = new Throwable();
            conn.setStackTrace(t);

            String stackTrace = SystemUtil.getStackTrace(t);
            synchronized (sConnectionStackCounter) {
                sConnectionStackCounter.increment(stackTrace);
            }
        }
        if (mbox != null)
            Db.registerDatabaseInterest(conn, mbox);

        ZimbraPerf.STOPWATCH_DB_CONN.stop(start);
        return conn;
    } catch (ServiceException se) {
        //if connection open fails unlock
        Db.getInstance().abortOpen(mboxId);
        throw se;
    }
}

From source file:org.apache.sqoop.manager.OracleManager.java

/**
 * Create a connection to the database; usually used only from within
 * getConnection(), which enforces a singleton guarantee around the
 * Connection object.//ww w.  j  a v  a  2  s . c o  m
 *
 * Oracle-specific driver uses READ_COMMITTED which is the weakest
 * semantics Oracle supports.
 */
protected Connection makeConnection() throws SQLException {

    Connection connection;
    String driverClass = getDriverClass();

    try {
        Class.forName(driverClass);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException("Could not load db driver class: " + driverClass);
    }

    String username = options.getUsername();
    String password = options.getPassword();
    String connectStr = options.getConnectString();

    connection = CACHE.getConnection(connectStr, username);
    if (null == connection) {
        // Couldn't pull one from the cache. Get a new one.
        LOG.debug("Creating a new connection for " + connectStr + ", using username: " + username);
        Properties connectionParams = options.getConnectionParams();
        if (connectionParams != null && connectionParams.size() > 0) {
            LOG.debug("User specified connection params. "
                    + "Using properties specific API for making connection.");

            Properties props = new Properties();
            if (username != null) {
                props.put("user", username);
            }

            if (password != null) {
                props.put("password", password);
            }

            props.putAll(connectionParams);
            connection = DriverManager.getConnection(connectStr, props);
        } else {
            LOG.debug("No connection paramenters specified. " + "Using regular API for making connection.");
            if (username == null) {
                connection = DriverManager.getConnection(connectStr);
            } else {
                connection = DriverManager.getConnection(connectStr, username, password);
            }
        }
    }

    // We only use this for metadata queries. Loosest semantics are okay.
    connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    // Setting session time zone
    setSessionTimeZone(connection);

    return connection;
}

From source file:edu.umd.cs.submitServer.servlets.UploadSubmission.java

public static Submission uploadSubmission(Project project, StudentRegistration studentRegistration,
        byte[] zipOutput, HttpServletRequest request, Timestamp submissionTimestamp, String clientTool,
        String clientVersion, String cvsTimestamp, SubmitServerDatabaseProperties db, Logger log)
        throws ServletException, IOException {

    Connection conn;/*from w ww.  j  av a  2s  . co  m*/
    try {
        conn = db.getConnection();
    } catch (SQLException e) {
        throw new ServletException(e);
    }
    Submission submission = null;
    boolean transactionSuccess = false;

    try {
        Integer baselinePK = project.getArchivePK();
        int testSetupPK = project.getTestSetupPK();
        byte baseLineSubmission[] = null;
        if (baselinePK != null && baselinePK.intValue() != 0) {
            baseLineSubmission = project.getBaselineZip(conn);
        } else if (testSetupPK != 0) {
            baseLineSubmission = Submission.lookupCanonicalSubmissionArchive(project.getProjectPK(), conn);
        }
        zipOutput = FixZip.adjustZipNames(baseLineSubmission, zipOutput);

        int archivePK = Submission.uploadSubmissionArchive(zipOutput, conn);

        synchronized (UPLOAD_LOCK) {
            final int NUMBER_OF_ATTEMPTS = 2;
            int attempt = 1;
            while (true) {
                try {
                    conn.setAutoCommit(false);
                    conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

                    submission = Submission.submit(archivePK, studentRegistration, project, cvsTimestamp,
                            clientTool, clientVersion, submissionTimestamp, conn);

                    conn.commit();
                    transactionSuccess = true;
                    break;
                } catch (SQLException e) {
                    conn.rollback();

                    if (attempt++ >= NUMBER_OF_ATTEMPTS) {
                        Submission.deleteAbortedSubmissionArchive(archivePK, conn);
                        throw e;
                    }

                }
            }
        }

    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn, db, log);
    }
    logSubmission(studentRegistration, zipOutput, submission);

    if (submission.getBuildStatus() == Submission.BuildStatus.NEW)
        WaitingBuildServer.offerSubmission(project, submission);
    return submission;
}