JDBC事务是在Java应用程序中与数据库交互时保持数据完整性的机制。JDBC提供了以下三个接口来管理事务:
- Connection 接口: 与数据库建立连接并提供多个事务管理方法,如 setAutoCommit(boolean autoCommit)、commit()、rollback() 等。
- Savepoint 接口: 用于将一个事务分解成多个可回滚的操作核心。
- TransactionManager 接口: 定义了javax.transaction.Transaction 实例的生命周期,并提供 begin()、commit()、rollback() 等方法。
public void transferFunds(int fromAccountId, int toAccountId, double amount) throws SQLException {
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false); // 关闭自动提交
// 扣除汇款账户余额
updateAccountBalance(conn, fromAccountId, -amount);
// 增加收款账户余额
updateAccountBalance(conn, toAccountId, amount);
conn.commit(); // 提交事务
} catch (SQLException e) {
if (conn != null) {
conn.rollback(); // 回滚事务
}
throw e;
} finally {
if (conn != null) {
conn.close(); // 关闭连接
}
}
}
// 更新账户余额
private void updateAccountBalance(Connection conn, int accountId, double deltaAmount) throws SQLException {
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement("UPDATE accounts SET balance = balance + ? WHERE id = ?");
pstmt.setDouble(1, deltaAmount);
pstmt.setInt(2, accountId);
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
我们通过调用 setAutoCommit(false) 来关闭自动提交模式,然后在整个操作完成之后使用 commit() 提交事务。如果操作过程中出现异常,则使用 rollback() 回滚事务。另外,我们还使用了 PreparedStatement 预编译语句来执行 SQL 查询,并通过 try-finally 块来确保资源的释放。