下面列出了java.sql.Connection#getTransactionIsolation ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Utility that verifies that the isolation level reported by the client
* is the same as evaluating 'VALUES CURRENT ISOLATION' and getting the
* isolation level from the EmbedConnection on the server.
* @param c Connection to check
* @throws java.sql.SQLException
*/
private void verifyCachedIsolation(Connection c) throws SQLException {
final int clientInt = c.getTransactionIsolation();
Statement s = createStatement();
final IsoLevel serverSql = new IsoLevel(s.executeQuery(
"SELECT * FROM ISOLATION_NAMES " +
"WHERE SQLNAME = (VALUES CURRENT ISOLATION)"));
final IsoLevel serverJdbc = new IsoLevel(s.executeQuery(
"SELECT * FROM ISOLATION_NAMES " +
"WHERE ISOLEVEL = GET_TRANSACTION_ISOLATION_JDBC()"));
final IsoLevel client = new IsoLevel(s.executeQuery("SELECT * FROM " +
"ISOLATION_NAMES WHERE ISOLEVEL = "+clientInt));
s.getResultSet().close();
s.close();
assertEquals(serverSql, client);
assertEquals(serverJdbc, client);
}
/**
* Setup up and run the auto-commit tests.
*
*
*
* @throws SQLException
*/
public void testAutoCommit() throws SQLException {
Connection conn = getConnection();
Statement s = conn.createStatement();
s.executeUpdate("create table AutoCommitTable (num int)");
s.executeUpdate("insert into AutoCommitTable values (1)");
s.executeUpdate("insert into AutoCommitTable values (2)");
int isolation = conn.getTransactionIsolation();
conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
checkSingleRSAutoCommit(conn);
checkSingleRSCloseCursorsAtCommit(conn);
conn.setTransactionIsolation(isolation);
s.executeUpdate("drop table AutoCommitTable");
s.close();
}
/**
* Checks locks for designated isolation level on the connection.
* Currently only supports TRANSACTION_READ_COMMITTED and
* TRANSACTION_READ_UNCOMMITTED
* @param conn Connection to test
* @param expectedIsoLevel expected isolation level
*
*/
private void assertIsoLocks(Connection conn, int expectedIsoLevel)
throws SQLException {
int conniso = conn.getTransactionIsolation();
assertEquals(expectedIsoLevel, conniso);
boolean selectTimedOut = selectTimesoutDuringUpdate(conn);
// expect a lock timeout for READ_COMMITTED
switch (conniso) {
case Connection.TRANSACTION_READ_UNCOMMITTED:
assertFalse(selectTimedOut); break;
case Connection.TRANSACTION_READ_COMMITTED:
assertTrue(selectTimedOut); break;
default:
System.out.println("No test support for isolation level");
}
}
private void printIsolationLevel(Connection connection) throws SQLException {
int isolationLevelIntegerValue = connection.getTransactionIsolation();
String isolationLevelStringValue = null;
switch (isolationLevelIntegerValue) {
case Connection.TRANSACTION_READ_UNCOMMITTED:
isolationLevelStringValue = "READ_UNCOMMITTE";
break;
case Connection.TRANSACTION_READ_COMMITTED:
isolationLevelStringValue = "READ_COMMITTED";
break;
case Connection.TRANSACTION_REPEATABLE_READ:
isolationLevelStringValue = "REPEATABLE_READ";
break;
case Connection.TRANSACTION_SERIALIZABLE:
isolationLevelStringValue = "SERIALIZABLE";
break;
}
LOGGER.info("Transaction isolation level: {}", isolationLevelStringValue);
}
/**
* execute with retries in case of node failures for transactions but not for
* non-transactional case
*/
protected static int executeUpdate(Statement stmt, String sql)
throws SQLException {
while (true) {
try {
if (sql != null) {
return stmt.executeUpdate(sql);
}
else {
return ((PreparedStatement)stmt).executeUpdate();
}
} catch (SQLException sqle) {
Connection conn = stmt.getConnection();
if (conn.getTransactionIsolation() == Connection.TRANSACTION_NONE) {
throw sqle;
}
String sqlState = sqle.getSQLState();
if (!"40XD0".equals(sqlState) && !"40XD2".equals(sqlState)) {
throw sqle;
}
}
}
}
public ConnectionConcierge(String name, Connection conn, boolean keepAlive) {
_name = name + s_mgr.getNextId();
_keepAlive = keepAlive;
try {
_autoCommit = conn.getAutoCommit();
_isolationLevel = conn.getTransactionIsolation();
_holdability = conn.getHoldability();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to get information from the connection object", e);
}
reset(conn);
}
public static Connection getDBConnection(DataSource dataSource) throws SQLException {
Connection dbConnection = dataSource.getConnection();
dbConnection.setAutoCommit(false);
if (dbConnection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
}
return dbConnection;
}
public DalConnection(Connection conn, boolean master, String shardId, DbMeta meta) throws SQLException {
this.oldIsolationLevel = conn.getTransactionIsolation();
this.conn = conn;
this.master = master;
this.shardId = shardId;
this.meta = meta;
this.logger = DasConfigureFactory.getLogger();
}
private void setIsolationLevel(Connection connection)
{
try
{
if (connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE)
{
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
}
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
}
public int fillAndExecutePreparedInsertStatements(List pstmts, List stmts, int sid)
throws SQLException {
int numInstrumentsPerSector = SectorPrms.getNumInstrumentsPerSector();
PreparedStatement pstmt = (PreparedStatement) pstmts.get(0);
String stmt = (String)stmts.get(0);
int results = 0;
for (int i = 0; i < numInstrumentsPerSector; i++) {
int id = sid * numInstrumentsPerSector + i; // unique
String typeName = Instrument.getInstrument(id);
pstmt.setString(1, typeName);
pstmt.setInt(2, sid);
//pstmt.setString(3, typeName);
if (logQueries) {
Log.getLogWriter().info("EXECUTING: " + stmt + " with id=" + typeName
+ " sector_id=" + sid);
}
results += positionQueryFactory.fillAndExecutePreparedInsertStatements(
(List)pstmts.get(1), (List)stmts.get(1), id);
pstmt.addBatch();
results++;
}
pstmt.executeBatch();
pstmt.clearBatch();
Connection c = pstmt.getConnection();
if (c.getTransactionIsolation() != Connection.TRANSACTION_NONE
&& SectorPrms.commitBatches()) {
c.commit();
}
return results;
}
public ConnectionConcierge(final String name, final Connection conn, final boolean keepAlive) {
_name = name + s_mgr.getNextId();
_keepAlive = keepAlive;
try {
_autoCommit = conn.getAutoCommit();
_isolationLevel = conn.getTransactionIsolation();
_holdability = conn.getHoldability();
} catch (final SQLException e) {
throw new CloudRuntimeException("Unable to get information from the connection object", e);
}
reset(conn);
}
/**
* Implementation of the SQL function GET_CYCLE_ISOLATION_JDBC.
* Cycles the isolation level on the default Connection.
* @return the new JDBC isolation level constant
* @throws java.sql.SQLException
*/
public static int getCycleIsolationJDBC()
throws SQLException {
Connection c = DriverManager.getConnection("jdbc:default:connection");
c.setTransactionIsolation(cycleIsolation().getIsoLevel());
println("getCycleIsolationJDBC() -> "+c.getTransactionIsolation());
return c.getTransactionIsolation();
}
protected void printIsolationLevel(Connection conn) {
try {
int isolation = conn.getTransactionIsolation();
String isoLevel;
switch (isolation) {
case Connection.TRANSACTION_NONE:
isoLevel = "TRANSACTION_NONE";
break;
case Connection.TRANSACTION_READ_COMMITTED:
isoLevel = "TRANSACTION_READ_COMMITTED";
break;
case Connection.TRANSACTION_REPEATABLE_READ:
isoLevel = "TRANSACTION_REPEATABLE_READ";
break;
case Connection.TRANSACTION_SERIALIZABLE:
isoLevel = "TRANSACTION_SERIALIZABLE";
break;
default:
isoLevel = "unknown";
}
Log.getLogWriter().info("the connection isolation level is " + isoLevel);
java.sql.SQLWarning w =conn.getWarnings();
SQLHelper.printSQLWarning(w);
} catch (SQLException se) {
}
}
private Connection getDBConnection(boolean shouldApplyTransaction) throws SQLException, UserStoreException {
Connection dbConnection = IdentityDatabaseUtil.getUserDBConnection();
if (dbConnection == null) {
throw new UserStoreException("Could not create a database connection to User database");
}
if (shouldApplyTransaction) {
dbConnection.setAutoCommit(false);
if (dbConnection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
}
}
return dbConnection;
}
final void openRealConnection() throws SQLException {
// first time we establish a connection
Connection rc = dataSource.getConnection(username, password, requestPassword);
this.realConnection = (EmbedConnection) rc;
defaultIsolationLevel = rc.getTransactionIsolation();
defaultReadOnly = rc.isReadOnly();
if (currentConnectionHandle != null)
realConnection.setApplicationConnection(currentConnectionHandle);
}
final void openRealConnection() throws SQLException {
// first time we establish a connection
Connection rc = dataSource.getConnection(username, password, requestPassword);
this.realConnection = (EmbedConnection) rc;
defaultIsolationLevel = rc.getTransactionIsolation();
defaultReadOnly = rc.isReadOnly();
if (currentConnectionHandle != null)
realConnection.setApplicationConnection(currentConnectionHandle);
}
/**
* Implementation of the SQL function GET_CYCLE_ISOLATION_JDBC.
* Cycles the isolation level on the default Connection.
* @return the new JDBC isolation level constant
* @throws java.sql.SQLException
*/
public static int getCycleIsolationJDBC()
throws SQLException {
Connection c = DriverManager.getConnection("jdbc:default:connection");
c.setTransactionIsolation(cycleIsolation().getIsoLevel());
println("getCycleIsolationJDBC() -> "+c.getTransactionIsolation());
return c.getTransactionIsolation();
}
/**
* Prepare the given Connection with the given transaction semantics.
* @param con the Connection to prepare
* @param definition the transaction definition to apply
* @return the previous isolation level, if any
* @throws SQLException if thrown by JDBC methods
* @see #resetConnectionAfterTransaction
*/
@Nullable
public static TransactionDefinition.Isolation prepareConnectionForTransaction(Connection con, @Nullable TransactionDefinition definition)
throws SQLException {
Objects.requireNonNull(con, "No Connection specified");
// Set read-only flag.
if (definition != null && definition.isReadOnly()) {
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Setting JDBC Connection [" + con + "] read-only");
}
con.setReadOnly(true);
} catch (SQLException | RuntimeException ex) {
Throwable exToCheck = ex;
while (exToCheck != null) {
if (exToCheck.getClass().getSimpleName().contains("Timeout")) {
// Assume it's a connection timeout that would otherwise get lost: e.g. from JDBC 4.0
throw ex;
}
exToCheck = exToCheck.getCause();
}
// "read-only not supported" SQLException -> ignore, it's just a hint anyway
LOGGER.debug("Could not set JDBC Connection read-only", ex);
}
}
// Apply specific isolation level, if any.
TransactionDefinition.Isolation previousIsolationLevel = null;
if (definition != null) {
TransactionDefinition.Isolation isolationLevel = definition.getIsolationLevel();
if (isolationLevel != TransactionDefinition.Isolation.DEFAULT) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Changing isolation level of JDBC Connection [" + con + "] to " +
isolationLevel);
}
int currentIsolation = con.getTransactionIsolation();
if (currentIsolation != isolationLevel.getCode()) {
previousIsolationLevel = TransactionDefinition.Isolation.valueOf(currentIsolation);
con.setTransactionIsolation(isolationLevel.getCode());
}
}
}
return previousIsolationLevel;
}
/**
* Check the default connection properties (auto-commit, transaction isolation),
* keeping them to be able to expose them correctly without fetching an actual
* JDBC Connection from the target DataSource.
* <p>This will be invoked once on startup, but also for each retrieval of a
* target Connection. If the check failed on startup (because the database was
* down), we'll lazily retrieve those settings.
* @param con the Connection to use for checking
* @throws SQLException if thrown by Connection methods
*/
protected synchronized void checkDefaultConnectionProperties(Connection con) throws SQLException {
if (this.defaultAutoCommit == null) {
this.defaultAutoCommit = con.getAutoCommit();
}
if (this.defaultTransactionIsolation == null) {
this.defaultTransactionIsolation = con.getTransactionIsolation();
}
}
/**
* Check the default connection properties (auto-commit, transaction isolation),
* keeping them to be able to expose them correctly without fetching an actual
* JDBC Connection from the target DataSource.
* <p>This will be invoked once on startup, but also for each retrieval of a
* target Connection. If the check failed on startup (because the database was
* down), we'll lazily retrieve those settings.
*
* @param con the Connection to use for checking
* @throws SQLException if thrown by Connection methods
*/
protected synchronized void checkDefaultConnectionProperties(Connection con) throws SQLException {
if (this.defaultAutoCommit == null) {
this.defaultAutoCommit = con.getAutoCommit();
}
if (this.defaultTransactionIsolation == null) {
this.defaultTransactionIsolation = con.getTransactionIsolation();
}
}