因为我最近能够在 JDBC&交易通常只涵盖非常简单的案例:
我想知道JDBC事务的正确模板是怎样的,特别是在涉及 SELECT 语句的情况下。
据我所知,通用模板类似于:
final int previousIsolationLevel = connection.getTransactionIsolation();
try {
connection.setTransactionIsolation(desiredIsolationLevel);
connection.setAutoCommit(false); // starting transaction
// executing UPDATE / INSERT statements here using ps.executeUpdate(...)
// executing SELECT statements and storing references to result sets like:
// ResultSet rs1 = ps1.executeQuery(...);
// ResultSet rs2 = ps2.executeQuery(...);
// ...
// ResultSet rsN = psN.executeQuery(...);
connection.commit(); // committing transaction
// reading data from rs1, ... , rsN AFTER commit like
// while(rs1.next()) { ... }, while(rs2.next()) { ... }, ...
} catch (final Throwable ex) {
connection.rollback(); // rolling back the transaction upon any exception
// doing exception-handling stuff
} finally {
connection.setAutoCommit(true); // setting auto-commit mode back to true
connection.setTransactionIsolation(previousIsolationLevel); // setting transaction isolation to previous value
}
所以问题是:
注意:我想找到最通用的方法,但如果它是特定于供应商的,我正在使用 MySQL 数据库。当然,我对这个话题的任何帮助感兴趣并感激不尽!