List of usage examples for java.sql Connection TRANSACTION_SERIALIZABLE
int TRANSACTION_SERIALIZABLE
To view the source code for java.sql Connection TRANSACTION_SERIALIZABLE.
Click Source Link
From source file:backtype.storm.scheduler.adaptive.DataManager.java
public int checkTopology(String stormId) throws Exception { Connection connection = null; Statement statement = null;//from w w w . ja v a 2s . co m ResultSet resultSet = null; int id = -1; logger.debug("Going to check topology " + stormId); try { connection = getConnection(); connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); connection.setAutoCommit(false); statement = connection.createStatement(); String sql = "select id from topology where storm_id = '" + stormId + "'"; logger.debug("SQL query: " + sql); resultSet = statement.executeQuery(sql); if (resultSet.next()) { id = resultSet.getInt(1); logger.debug("Topology found, id: " + id); } else { logger.debug("Topology not found, let's create it"); resultSet.close(); sql = "insert into topology(storm_id) values('" + stormId + "')"; logger.debug("SQL script: " + sql); statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); logger.debug("Retrieving generated id..."); resultSet = statement.getGeneratedKeys(); if (resultSet.next()) { id = resultSet.getInt(1); logger.debug("Ok, id: " + id); } else { throw new Exception("Cannot retrieve generated key"); } } connection.commit(); } catch (Exception e) { connection.rollback(); logger.error("An error occurred checking a topology", e); throw e; } finally { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } return id; }
From source file:com.amazon.carbonado.repo.jdbc.LoggingConnection.java
public void setTransactionIsolation(int level) throws SQLException { String levelStr;/*from w w w. j ava2 s. c o m*/ switch (level) { default: levelStr = String.valueOf(level); break; case Connection.TRANSACTION_NONE: levelStr = "TRANSACTION_NONE"; break; case Connection.TRANSACTION_READ_UNCOMMITTED: levelStr = "TRANSACTION_READ_UNCOMMITTED"; break; case Connection.TRANSACTION_READ_COMMITTED: levelStr = "TRANSACTION_READ_COMMITTED"; break; case Connection.TRANSACTION_REPEATABLE_READ: levelStr = "TRANSACTION_REPEATABLE_READ"; break; case Connection.TRANSACTION_SERIALIZABLE: levelStr = "TRANSACTION_SERIALIZABLE"; break; } mLog.debug("Connection.setTransactionIsolation(" + levelStr + ')'); mCon.setTransactionIsolation(level); }
From source file:com.oltpbenchmark.WorkloadConfiguration.java
public void setIsolationMode(String mode) { if (mode.equals("TRANSACTION_SERIALIZABLE")) this.isolationMode = Connection.TRANSACTION_SERIALIZABLE; else if (mode.equals("TRANSACTION_READ_COMMITTED")) this.isolationMode = Connection.TRANSACTION_READ_COMMITTED; else if (mode.equals("TRANSACTION_REPEATABLE_READ")) this.isolationMode = Connection.TRANSACTION_REPEATABLE_READ; else if (mode.equals("TRANSACTION_READ_UNCOMMITTED")) this.isolationMode = Connection.TRANSACTION_READ_UNCOMMITTED; else if (!mode.isEmpty()) System.out.println("Indefined isolation mode, set to default [TRANSACTION_SERIALIZABLE]"); }
From source file:chat.Models.java
void start(boolean execute) throws Exception { hib = (SessionImpl) factory.openSession(); dialect = hib.getFactory().getDialect(); conn = hib.getJDBCContext().borrowConnection(); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); hib.beginTransaction();//w w w . j a v a2 s. c o m if (execute) stat = conn.createStatement(); }
From source file:com.cloudera.sqoop.metastore.hsqldb.HsqldbJobStorage.java
protected void init() throws IOException { try {/* ww w. j av a 2 s .c om*/ // Load/initialize the JDBC driver. Class.forName(DB_DRIVER_CLASS); } catch (ClassNotFoundException cnfe) { throw new IOException("Could not load HSQLDB JDBC driver", cnfe); } try { if (null == metastoreUser) { this.connection = DriverManager.getConnection(metastoreConnectStr); } else { this.connection = DriverManager.getConnection(metastoreConnectStr, metastoreUser, metastorePassword); } connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); connection.setAutoCommit(false); // Initialize the root schema. if (!rootTableExists()) { createRootTable(); } // Check the schema version. String curStorageVerStr = getRootProperty(STORAGE_VERSION_KEY, null); int actualStorageVer = -1; try { actualStorageVer = Integer.valueOf(curStorageVerStr); } catch (NumberFormatException nfe) { LOG.warn("Could not interpret as a number: " + curStorageVerStr); } if (actualStorageVer != CUR_STORAGE_VERSION) { LOG.error("Can not interpret metadata schema"); LOG.error("The metadata schema version is " + curStorageVerStr); LOG.error("The highest version supported is " + CUR_STORAGE_VERSION); LOG.error("To use this version of Sqoop, " + "you must downgrade your metadata schema."); throw new IOException("Invalid metadata version."); } // Initialize the versioned schema. initV0Schema(); } catch (SQLException sqle) { if (null != connection) { try { connection.rollback(); } catch (SQLException e2) { LOG.warn("Error rolling back transaction in error handler: " + e2); } } throw new IOException("Exception creating SQL connection", sqle); } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.OracleEngine.java
/** * Overrides {@link com.feedzai.commons.sql.abstraction.engine.AbstractDatabaseEngine#setTransactionIsolation()} This is because * Oracle does not support READ_UNCOMMITTED e REPEATABLE_READ. * * @throws SQLException If a database access error occurs. *//* w w w . j a va 2 s . c om*/ @Override protected void setTransactionIsolation() throws SQLException { int isolation = properties.getIsolationLevel(); if (isolation == Connection.TRANSACTION_READ_UNCOMMITTED) { isolation = Connection.TRANSACTION_READ_COMMITTED; } if (isolation == Connection.TRANSACTION_REPEATABLE_READ) { isolation = Connection.TRANSACTION_SERIALIZABLE; } conn.setTransactionIsolation(isolation); }
From source file:com.glaf.core.jdbc.connection.TomcatJdbcConnectionProvider.java
protected void parsePoolProperties(PoolConfiguration poolProperties, Properties properties) { String value = null;//from w ww . j a v a 2s . c o m 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:com.feedzai.commons.sql.abstraction.engine.configuration.PdbProperties.java
/** * Gets the isolation level./*from w w w . j av a 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.opendatakit.persistence.engine.pgres.TaskLockImpl.java
private TaskLockTable doTransaction(TaskLockTable entity, long l) throws ODKEntityNotFoundException, ODKTaskLockException { boolean first; final List<String> stmts = new ArrayList<String>(); String uri = entity.getUri(); StringBuilder stringBuilder = new StringBuilder(); String tableName = K_BQ + datastore.getDefaultSchemaName() + K_BQ + "." + K_BQ + TaskLockTable.TABLE_NAME + K_BQ;/*from w w w. ja v a2s.co m*/ stringBuilder.append("'").append(user.getUriUser().replaceAll("'", "''")).append("'"); String uriUserInline = stringBuilder.toString(); stringBuilder.setLength(0); stringBuilder.append("'").append(uri.replaceAll("'", "''")).append("'"); String uriLockInline = stringBuilder.toString(); stringBuilder.setLength(0); stringBuilder.append("'").append(entity.getFormId().replaceAll("'", "''")).append("'"); String formIdInline = stringBuilder.toString(); stringBuilder.setLength(0); stringBuilder.append("'").append(entity.getTaskType().replaceAll("'", "''")).append("'"); String taskTypeInline = stringBuilder.toString(); stringBuilder.setLength(0); stringBuilder.append("interval '").append(l).append(" milliseconds'"); String lifetimeIntervalMilliseconds = stringBuilder.toString(); stringBuilder.setLength(0); stringBuilder.append("LOCK TABLE ").append(tableName).append(" IN ACCESS EXCLUSIVE MODE"); stmts.add(stringBuilder.toString()); stringBuilder.setLength(0); dam.recordPutUsage(TaskLockTable.TABLE_NAME); if (!entity.isFromDatabase()) { // insert a new record (prospective lock) stringBuilder.append("INSERT INTO "); stringBuilder.append(tableName); stringBuilder.append(" ("); first = true; for (DataField dataField : entity.getFieldList()) { if (!first) { stringBuilder.append(","); } first = false; stringBuilder.append(K_BQ); stringBuilder.append(dataField.getName()); stringBuilder.append(K_BQ); } first = true; stringBuilder.append(") VALUES ( "); for (DataField dataField : entity.getFieldList()) { if (!first) { stringBuilder.append(","); } first = false; if (dataField.equals(entity.creationDate) || dataField.equals(entity.lastUpdateDate)) { stringBuilder.append("NOW()"); } else if (dataField.equals(entity.creatorUriUser) || dataField.equals(entity.lastUpdateUriUser)) { stringBuilder.append(uriUserInline); } else if (dataField.equals(entity.formId)) { stringBuilder.append(formIdInline); } else if (dataField.equals(entity.taskType)) { stringBuilder.append(taskTypeInline); } else if (dataField.equals(entity.primaryKey)) { stringBuilder.append(uriLockInline); } else if (dataField.equals(entity.expirationDateTime)) { stringBuilder.append(" NOW() + "); stringBuilder.append(lifetimeIntervalMilliseconds); } else { throw new IllegalStateException("unexpected case " + dataField.getName()); } } stringBuilder.append(")"); stmts.add(stringBuilder.toString()); stringBuilder.setLength(0); } else { // update existing record (prospective lock) stringBuilder.append("UPDATE "); stringBuilder.append(tableName); stringBuilder.append(" SET "); first = true; for (DataField f : entity.getFieldList()) { if (f == entity.primaryKey) continue; if (!first) { stringBuilder.append(","); } first = false; stringBuilder.append(K_BQ); stringBuilder.append(f.getName()); stringBuilder.append(K_BQ); stringBuilder.append(" = "); if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) { stringBuilder.append("NOW()"); } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) { stringBuilder.append(uriUserInline); } else if (f.equals(entity.formId)) { stringBuilder.append(formIdInline); } else if (f.equals(entity.taskType)) { stringBuilder.append(taskTypeInline); } else if (f.equals(entity.primaryKey)) { stringBuilder.append(uriLockInline); } else if (f.equals(entity.expirationDateTime)) { stringBuilder.append(" NOW() + "); stringBuilder.append(lifetimeIntervalMilliseconds); } else { throw new IllegalStateException("unexpected case " + f.getName()); } } stringBuilder.append(" WHERE "); stringBuilder.append(K_BQ); stringBuilder.append(entity.primaryKey.getName()); stringBuilder.append(K_BQ); stringBuilder.append(" = "); stringBuilder.append(uriLockInline); stmts.add(stringBuilder.toString()); stringBuilder.setLength(0); } // delete stale locks (don't care who's) dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); stringBuilder.append("DELETE FROM ").append(tableName).append(" WHERE "); stringBuilder.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ).append(" <= NOW()"); stmts.add(stringBuilder.toString()); stringBuilder.setLength(0); // delete prospective locks which are not the oldest for that resource and // task type dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); stringBuilder.append("DELETE FROM ").append(tableName).append(" WHERE "); stringBuilder.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND "); stringBuilder.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ") .append(taskTypeInline).append(" AND "); stringBuilder.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ); stringBuilder.append(" > (SELECT MIN(t3.").append(K_BQ).append(entity.expirationDateTime.getName()) .append(K_BQ); stringBuilder.append(") FROM ").append(tableName).append(" AS t3 WHERE t3."); stringBuilder.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND t3."); stringBuilder.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ") .append(taskTypeInline).append(")"); stmts.add(stringBuilder.toString()); stringBuilder.setLength(0); // delete our entry if it collides with another entry with exactly // this time. stringBuilder.append("DELETE FROM ").append(tableName).append(" WHERE "); stringBuilder.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND "); stringBuilder.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ") .append(taskTypeInline).append(" AND "); stringBuilder.append(K_BQ).append(entity.primaryKey.getName()).append(K_BQ).append(" = ") .append(uriLockInline).append(" AND "); stringBuilder.append("1 < (SELECT COUNT(t3.").append(K_BQ).append(entity.expirationDateTime.getName()) .append(K_BQ); stringBuilder.append(") FROM ").append(tableName).append(" AS t3 WHERE t3."); stringBuilder.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND t3."); stringBuilder.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ") .append(taskTypeInline).append(")"); stmts.add(stringBuilder.toString()); stringBuilder.setLength(0); // assert: only the lock that holds the resource for that task type appears // in the task lock table TaskLockTable relation; try { JdbcTemplate jdbc = datastore.getJdbcConnection(); jdbc.execute(new ConnectionCallback<Object>() { @Override public Object doInConnection(Connection conn) throws SQLException, DataAccessException { boolean oldAutoCommitValue = conn.getAutoCommit(); int oldTransactionValue = conn.getTransactionIsolation(); try { conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); Statement stmt = conn.createStatement(); for (String s : stmts) { // for debugging: LogFactory.getLog(TaskLockImpl.class).info(s); stmt.execute(s); } conn.commit(); } catch (PSQLException e) { e.printStackTrace(); conn.rollback(); } catch (Exception e) { e.printStackTrace(); conn.rollback(); } conn.setTransactionIsolation(oldTransactionValue); conn.setAutoCommit(oldAutoCommitValue); return null; } }); relation = TaskLockTable.assertRelation(datastore, user); } catch (Exception e) { throw new ODKTaskLockException(PERSISTENCE_LAYER_PROBLEM, e); } return (TaskLockTable) datastore.getEntity(relation, entity.getUri(), user); }
From source file:io.vitess.jdbc.VitessMySQLDatabaseMetadata.java
public boolean supportsTransactionIsolationLevel(int level) throws SQLException { switch (level) { case Connection.TRANSACTION_READ_COMMITTED: case Connection.TRANSACTION_READ_UNCOMMITTED: case Connection.TRANSACTION_REPEATABLE_READ: case Connection.TRANSACTION_SERIALIZABLE: return true; default://from w w w.ja v a 2 s. c o m return false; } }