- 最終更新
- 2026/08/17
3秒でわかる
JDBCで自動コミットの有無を切り替えるメソッド。複数のSQLをひとつのトランザクションとしてまとめたいときに false にします。
30秒図解
もう少し詳しく
どういうものか
setAutoCommit は、Java のConnection がsetAutoCommit(false) をcommit() をrollback() を
なぜ必要か
現実の処理は、
性能上の
具体例
Connection conn = dataSource.getConnection();
try {
conn.setAutoCommit(false);
try (PreparedStatement out = conn.prepareStatement(
"UPDATE accounts SET balance = balance - ? WHERE id = ?")) {
out.setInt(1, 5000);
out.setString(2, "A001");
out.executeUpdate();
}
try (PreparedStatement in = conn.prepareStatement(
"UPDATE accounts SET balance = balance + ? WHERE id = ?")) {
in.setInt(1, 5000);
in.setString(2, "B002");
in.executeUpdate();
}
conn.commit(); // ここではじめて両方が確定する
} catch (SQLException e) {
conn.rollback(); // 片方だけ成立した状態を残さない
throw e;
} finally {
conn.setAutoCommit(true);
conn.close();
}つまずきやすいところ
いちばんcommit() の
次に、
もう
似た用語との違い
| 語 | 位置づけ |
|---|---|
| setAutoCommit(false) | トランザクションの |
| commit | それまでの |
| rollback | それまでの |
| @Transactional | Spring が |


