Last active
August 29, 2015 14:01
-
-
Save froop/8fa210986fcfbeb2376f to your computer and use it in GitHub Desktop.
[Java][DB] DerbyのTRANSACTION_READ_COMMITTEDはSELECTで待たされる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<dataset> | |
<sample id="1" name="name1" /> | |
</dataset> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Derbyでは更新中の行をTRANSACTION_READ_COMMITTEDでSELECTしたときに待ちが発生する. | |
* OracleやMySQLでは待たずに更新前の情報を取得するので違う動作。DB2はDerbyと同じ? | |
*/ | |
public class DatabaseLockReadTest { | |
private Connection lockedConn; | |
@Before | |
public void setUp() throws Exception { | |
setLocksWaitTimeout(); | |
lockedConn = getConnection(); | |
lockedConn.setAutoCommit(false); | |
updateNotCommit(); | |
} | |
@After | |
public void tearDown() throws Exception { | |
lockedConn.rollback(); | |
lockedConn.close(); | |
} | |
@Test | |
public void testReadCommitted() { | |
try { | |
String name = selectLockedRow(Connection.TRANSACTION_READ_COMMITTED); | |
fail(name); | |
} catch (SQLException e) { | |
assertThat(e.getSQLState(), is("40XL1")); | |
} | |
} | |
@Test | |
public void testReadUncommitted() throws SQLException { | |
String name = selectLockedRow(Connection.TRANSACTION_READ_UNCOMMITTED); | |
assertThat(name, is("updated")); | |
} | |
private void setLocksWaitTimeout() throws SQLException { | |
try (Connection conn = getConnection(); | |
Statement stmt = conn.createStatement()) { | |
stmt.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.locks.waitTimeout', '1')"); | |
} | |
} | |
private void updateNotCommit() throws SQLException { | |
PreparedStatement stmt = lockedConn.prepareStatement("UPDATE sample SET name='updated' WHERE id=1"); | |
stmt.execute(); | |
} | |
private String selectLockedRow(int isolationLevel) throws SQLException { | |
try (Connection conn = getConnection()) { | |
conn.setTransactionIsolation(isolationLevel); | |
ResultSet rs = conn.createStatement().executeQuery("SELECT name FROM sample WHERE id=1"); | |
rs.next(); | |
return rs.getString("name"); | |
} | |
} | |
private Connection getConnection() throws SQLException { | |
return DriverManager.getConnection("jdbc:derby:data/derby/sample"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment