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

@Override
public List<User> findAll() {
    try {//from  ww w . ja v a  2s  .  c om
        List<User> users = new ArrayList<User>();

        Connection connection = createConnectionBuilder()
                .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED).build();

        Statement statement = connection.createStatement();

        ResultSet resultSet = statement.executeQuery(FIND_ALL_USERS_SQL);

        if (resultSet != null) {
            int rowIndex = 0;

            while (resultSet.next()) {
                users.add(mapUser(resultSet, rowIndex));
            }
        }

        return users;
    } catch (SQLException e) {
        throw createDataAccessException("Failed to find all users!", e);
    }
}

From source file:de.hybris.platform.test.HJMPOptimisticConcurrencyPerformanceTest.java

private void prepareTransaction(final Transaction tx) {
    tx.setTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED);
    tx.enableDelayedStore(true);
}

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

private void setupDBCP2basic() throws SQLException {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(dbDriver);/*from w ww.j av  a 2 s.c  om*/
    ds.setUsername("sa");
    ds.setPassword("");
    ds.setUrl(jdbcURL);
    ds.setMaxTotal(maxPoolSize);
    ds.setDefaultAutoCommit(false);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    ds.getConnection().createStatement().execute("CREATE TABLE IF NOT EXISTS test (column varchar);");
    DS = ds;
}

From source file:org.apache.synapse.config.xml.AbstractDBMediatorFactory.java

/**
 * Create a custom DataSource using the specified properties and Apache DBCP
 * @param pool the toplevel 'pool' element that holds DataSource information
 * @param mediator the mediator to store properties for serialization
 * @return a DataSource created using specified properties
 *///from   w w  w.jav  a2s.  com
private DataSource createCustomDataSource(OMElement pool, AbstractDBMediator mediator) {

    BasicDataSource ds = new BasicDataSource();

    // load the minimum required properties
    ds.setDriverClassName(getValue(pool, DRIVER_Q));
    ds.setUsername(getValue(pool, USER_Q));
    ds.setPassword(getValue(pool, PASS_Q));
    ds.setUrl(getValue(pool, URL_Q));

    //save loaded properties for later
    mediator.addDataSourceProperty(DRIVER_Q, getValue(pool, DRIVER_Q));
    mediator.addDataSourceProperty(URL_Q, getValue(pool, URL_Q));
    mediator.addDataSourceProperty(USER_Q, getValue(pool, USER_Q));
    mediator.addDataSourceProperty(PASS_Q, getValue(pool, PASS_Q));

    Iterator props = pool.getChildrenWithName(PROP_Q);
    while (props.hasNext()) {

        OMElement prop = (OMElement) props.next();
        String name = prop.getAttribute(ATT_NAME).getAttributeValue();
        String value = prop.getAttribute(ATT_VALUE).getAttributeValue();
        // save property for later
        mediator.addDataSourceProperty(name, value);

        if ("autocommit".equals(name)) {
            if ("true".equals(value)) {
                ds.setDefaultAutoCommit(true);
            } else if ("false".equals(value)) {
                ds.setDefaultAutoCommit(false);
            }
        } else if ("isolation".equals(name)) {
            try {
                if ("Connection.TRANSACTION_NONE".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
                } else if ("Connection.TRANSACTION_READ_COMMITTED".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                } else if ("Connection.TRANSACTION_READ_UNCOMMITTED".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
                } else if ("Connection.TRANSACTION_REPEATABLE_READ".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
                } else if ("Connection.TRANSACTION_SERIALIZABLE".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                }
            } catch (NumberFormatException ignore) {
            }
        } else if ("initialsize".equals(name)) {
            try {
                ds.setInitialSize(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxactive".equals(name)) {
            try {
                ds.setMaxActive(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxidle".equals(name)) {
            try {
                ds.setMaxIdle(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxopenstatements".equals(name)) {
            try {
                ds.setMaxOpenPreparedStatements(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxwait".equals(name)) {
            try {
                ds.setMaxWait(Long.parseLong(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("minidle".equals(name)) {
            try {
                ds.setMinIdle(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("poolstatements".equals(name)) {
            if ("true".equals(value)) {
                ds.setPoolPreparedStatements(true);
            } else if ("false".equals(value)) {
                ds.setPoolPreparedStatements(false);
            }
        } else if ("testonborrow".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestOnBorrow(true);
            } else if ("false".equals(value)) {
                ds.setTestOnBorrow(false);
            }
        } else if ("testonreturn".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestOnReturn(true);
            } else if ("false".equals(value)) {
                ds.setTestOnReturn(false);
            }
        } else if ("testwhileidle".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestWhileIdle(true);
            } else if ("false".equals(value)) {
                ds.setTestWhileIdle(false);
            }
        } else if ("validationquery".equals(name)) {
            ds.setValidationQuery(value);
        }
    }
    return ds;
}

From source file:com.glaf.core.jdbc.connection.TomcatJdbcConnectionProvider.java

protected void parsePoolProperties(PoolConfiguration poolProperties, Properties properties) {

    String value = null;/*from  w  w  w .j ava2s.c om*/

    value = properties.getProperty(ConnectionConstants.PROP_DEFAULTAUTOCOMMIT);
    if (value != null) {
        poolProperties.setDefaultAutoCommit(Boolean.valueOf(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_DEFAULTREADONLY);
    if (value != null) {
        poolProperties.setDefaultReadOnly(Boolean.valueOf(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_DEFAULTTRANSACTIONISOLATION);
    if (value != null) {
        int level = ConnectionConstants.UNKNOWN_TRANSACTIONISOLATION;
        if ("NONE".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_NONE;
        } else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_READ_COMMITTED;
        } else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_READ_UNCOMMITTED;
        } else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_REPEATABLE_READ;
        } else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_SERIALIZABLE;
        } else {
            try {
                level = Integer.parseInt(value);
            } catch (NumberFormatException e) {
                System.err.println("Could not parse defaultTransactionIsolation: " + value);
                System.err.println("WARNING: defaultTransactionIsolation not set");
                System.err.println("using default value of database driver");
                level = ConnectionConstants.UNKNOWN_TRANSACTIONISOLATION;
            }
        }
        poolProperties.setDefaultTransactionIsolation(level);
    }

    value = properties.getProperty(ConnectionConstants.PROP_DEFAULTCATALOG);
    if (value != null) {
        poolProperties.setDefaultCatalog(value);
    }

    value = properties.getProperty(ConnectionConstants.PROP_MAXACTIVE);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setMaxActive(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_MAXIDLE);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setMaxIdle(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_MINIDLE);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setMinIdle(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_INITIALSIZE);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setInitialSize(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_MAXWAIT);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setMaxWait(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_TESTONBORROW);
    if (value != null) {
        poolProperties.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(ConnectionConstants.PROP_TESTONRETURN);
    if (value != null) {
        poolProperties.setTestOnReturn(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(ConnectionConstants.PROP_TESTONCONNECT);
    if (value != null) {
        poolProperties.setTestOnConnect(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(ConnectionConstants.PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setTimeBetweenEvictionRunsMillis(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_NUMTESTSPEREVICTIONRUN);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setNumTestsPerEvictionRun(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_MINEVICTABLEIDLETIMEMILLIS);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setMinEvictableIdleTimeMillis(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_TESTWHILEIDLE);
    if (value != null) {
        poolProperties.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(ConnectionConstants.PROP_VALIDATOR_CLASS_NAME);
    if (value != null) {
        poolProperties.setValidatorClassName(value);
    }

    value = properties.getProperty(ConnectionConstants.PROP_VALIDATIONINTERVAL);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setValidationInterval(Long.parseLong(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
    if (value != null) {
        poolProperties.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(ConnectionConstants.PROP_REMOVEABANDONED);
    if (value != null) {
        poolProperties.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(ConnectionConstants.PROP_REMOVEABANDONEDTIMEOUT);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setRemoveAbandonedTimeout(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_LOGABANDONED);
    if (value != null) {
        poolProperties.setLogAbandoned(Boolean.valueOf(value).booleanValue());
    }

    if (poolProperties.getUsername() != null) {
        poolProperties.getDbProperties().setProperty("user", poolProperties.getUsername());
    }
    if (poolProperties.getPassword() != null) {
        poolProperties.getDbProperties().setProperty("password", poolProperties.getPassword());
    }

    value = properties.getProperty(ConnectionConstants.PROP_INITSQL);
    if (value != null) {
        poolProperties.setInitSQL(value);
    }

    value = properties.getProperty(ConnectionConstants.PROP_INTERCEPTORS);
    if (value != null) {
        poolProperties.setJdbcInterceptors(value);
    }

    value = properties.getProperty(ConnectionConstants.PROP_JMX_ENABLED);
    if (value != null) {
        poolProperties.setJmxEnabled(Boolean.parseBoolean(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_FAIR_QUEUE);
    if (value != null) {
        poolProperties.setFairQueue(Boolean.parseBoolean(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_USE_EQUALS);
    if (value != null) {
        poolProperties.setUseEquals(Boolean.parseBoolean(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_ABANDONWHENPERCENTAGEFULL);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setAbandonWhenPercentageFull(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_MAXAGE);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setMaxAge(Long.parseLong(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_USE_CON_LOCK);
    if (value != null) {
        poolProperties.setUseLock(Boolean.parseBoolean(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_SUSPECT_TIMEOUT);
    if (value != null && StringUtils.isNumeric(value)) {
        poolProperties.setSuspectTimeout(Integer.parseInt(value));
    }

    value = properties.getProperty(ConnectionConstants.PROP_ALTERNATE_USERNAME_ALLOWED);
    if (value != null) {
        poolProperties.setAlternateUsernameAllowed(Boolean.parseBoolean(value));
    }

}

From source file:org.spring.data.gemfire.app.dao.provider.JdbcUserDao.java

@Override
public User save(final User user) {
    final boolean update = exists(user.getUsername());

    final String SQL = (update ? UPDATE_USER_SQL : INSERT_USER_SQL);

    Connection connection = createConnectionBuilder().setAutoCommit(false)
            .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED).build();

    try {//from www .  j av a  2s  . co m
        PreparedStatement statement = connection.prepareStatement(SQL);

        statement = (update ? prepareUpdate(statement, user) : prepareInsert(statement, user));
        statement.executeUpdate();

        connection.commit();

        return user;
    } catch (SQLException e) {
        rollback(connection);

        throw createDataAccessException(
                String.format("Failed to save (%1$s) User (%2$s)!", (update ? "UPDATE" : "INSERT"), user), e);
    } finally {
        JdbcUtils.closeConnection(connection);
    }
}

From source file:org.wso2.carbon.user.core.hybrid.HybridRoleManager.java

/**
 * @param filter/* w  w  w . j  a  v a  2 s. co m*/
 * @return
 * @throws UserStoreException
 */
public String[] getHybridRoles(String filter) throws UserStoreException {

    Connection dbConnection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;

    String sqlStmt = HybridJDBCConstants.GET_ROLES;
    int maxItemLimit = UserCoreConstants.MAX_USER_ROLE_LIST;
    int searchTime = UserCoreConstants.MAX_SEARCH_TIME;

    try {
        maxItemLimit = Integer.parseInt(
                realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_ROLE_LIST));
    } catch (Exception e) {
        maxItemLimit = DEFAULT_MAX_ROLE_LIST_SIZE;
    }

    try {
        searchTime = Integer.parseInt(
                realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_SEARCH_TIME));
    } catch (Exception e) {
        searchTime = DEFAULT_MAX_SEARCH_TIME;
    }

    try {
        if (filter != null && filter.trim().length() != 0) {
            filter = filter.trim();
            filter = filter.replace("*", "%");
            filter = filter.replace("?", "_");
        } else {
            filter = "%";
        }

        dbConnection = DatabaseUtil.getDBConnection(dataSource);

        if (dbConnection == null) {
            throw new UserStoreException("null connection");
        }

        dbConnection.setAutoCommit(false);
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setString(1, filter);
        if (sqlStmt.contains(UserCoreConstants.UM_TENANT_COLUMN)) {
            prepStmt.setInt(2, tenantId);
        }
        prepStmt.setMaxRows(maxItemLimit);
        try {
            prepStmt.setQueryTimeout(searchTime);
        } catch (Exception e) {
            // this can be ignored since timeout method is not implemented
            log.debug(e);
        }
        List<String> filteredRoles = new ArrayList<String>();

        try {
            rs = prepStmt.executeQuery();
        } catch (SQLException e) {
            log.error("Error while retrieving roles from Internal JDBC role store", e);
            // May be due time out, therefore ignore this exception
        }

        if (rs != null) {
            while (rs.next()) {
                String name = rs.getString(1);
                // Append the domain
                if (!name.contains(UserCoreConstants.DOMAIN_SEPARATOR)) {
                    name = UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR + name;
                }
                filteredRoles.add(name);
            }
        }
        return filteredRoles.toArray(new String[filteredRoles.size()]);
    } catch (SQLException e) {
        String errorMessage = "Error occurred while getting hybrid roles from filter : " + filter;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
    }
}

From source file:org.jxstar.dao.pool.PooledConnection.java

/**
 * ???JDBC/*from  w ww .java  2s  .  co m*/
 * Connection.TRANSACTION_NONE
 *       ????
 * Connection.TRANSACTION_READ_UNCOMMITTED
 *       ?????????
 * Connection.TRANSACTION_READ_COMMITTED(?)
 *       ????????? 
 * Connection.TRANSACTION_REPEATABLE_READ
 *       ?????????
 * Connection.TRANSACTION_SERIALIZABLE
 *       ????????
 * 
 * @param sTranLevel
 * @return
 */
private int getTranLevelConstant(String sTranLevel) {
    if (sTranLevel == null || sTranLevel.length() == 0) {
        return Connection.TRANSACTION_READ_COMMITTED;
    }

    String sTmpLevel = sTranLevel.toUpperCase();
    if (sTmpLevel.equals("TRANSACTION_NONE")) {
        return Connection.TRANSACTION_NONE;
    } else if (sTmpLevel.equals("TRANSACTION_READ_UNCOMMITTED")) {
        return Connection.TRANSACTION_READ_UNCOMMITTED;
    } else if (sTmpLevel.equals("TRANSACTION_READ_COMMITTED")) {
        return Connection.TRANSACTION_READ_COMMITTED;
    } else if (sTmpLevel.equals("TRANSACTION_REPEATABLE_READ")) {
        return Connection.TRANSACTION_REPEATABLE_READ;
    } else if (sTmpLevel.equals("TRANSACTION_SERIALIZABLE")) {
        return Connection.TRANSACTION_SERIALIZABLE;
    }

    return Connection.TRANSACTION_READ_COMMITTED;
}

From source file:nl.strohalm.cyclos.setup.DataBaseConfiguration.java

/**
 * Initialize some common properties for Hibernate
 *//*w w w  .j ava  2s.  c om*/
private void initCommonProperties(final Properties properties) {
    // The transaction isolation level
    if (StringUtils.isEmpty(properties.getProperty("hibernate.connection.isolation"))) {
        properties.setProperty("hibernate.connection.isolation", "" + Connection.TRANSACTION_READ_COMMITTED);
    }

    final boolean secondLevelCacheEnabled = Boolean
            .parseBoolean(properties.getProperty("hibernate.cache.use_second_level_cache", "false"));
    if (secondLevelCacheEnabled) {
        // The second level cache provider
        if (StringUtils.isEmpty(properties.getProperty("hibernate.cache.region.factory_class"))) {
            properties.setProperty("hibernate.cache.region.factory_class",
                    "net.sf.ehcache.hibernate.EhCacheRegionFactory");
        }
    }

    // For MySQL, set the character encoding to utf8
    String url = StringUtils.trimToNull(properties.getProperty("hibernate.connection.url"));
    if (url != null && url.toLowerCase().startsWith("jdbc:mysql:")) {
        if (!url.contains("useUnicode")) {
            url += (url.contains("?") ? "&" : "?") + "useUnicode=true";
        }
        if (!url.contains("characterEncoding")) {
            url += (url.contains("?") ? "&" : "?") + "characterEncoding=utf8";
        }
        properties.setProperty("hibernate.connection.url", url);
    }
}

From source file:org.apache.hadoop.hive.metastore.MultiHdfsInfo.java

public String getDatabase(String name) throws NoSuchObjectException, MetaException {
    Database db = null;//from  w  w  w  .  j av  a 2 s  . c  om
    Connection con;
    name = name.toLowerCase();

    try {
        con = JDBCStore.getSegmentConnection(name);
    } catch (MetaStoreConnectException e1) {
        LOG.error("get database error, db=" + name + ", msg=" + e1.getMessage());
        throw new NoSuchObjectException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("get database error, db=" + name + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    Statement stmt = null;

    try {
        con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

        stmt = con.createStatement();
        String sql = "SELECT name, hdfs_schema, description FROM DBS WHERE name='" + name + "'";

        ResultSet dbSet = stmt.executeQuery(sql);
        boolean isDBFind = false;

        while (dbSet.next()) {
            isDBFind = true;
            db = new Database();
            db.setName(dbSet.getString(1));
            db.setHdfsscheme(dbSet.getString(2));
            db.setDescription(dbSet.getString(3));
            break;
        }

        dbSet.close();

        if (!isDBFind) {
            LOG.error("get database error, db=" + name);
            throw new NoSuchObjectException("database " + name + " does not exist!");
        }
    } catch (SQLException sqlex) {
        sqlex.printStackTrace();
        throw new MetaException(sqlex.getMessage());
    } finally {
        JDBCStore.closeStatement(stmt);
        JDBCStore.closeConnection(con);
    }

    return db.getHdfsscheme();
}