借书/还书/续借/逾期管理
This commit is contained in:
@@ -13,6 +13,11 @@ public final class JdbcUtil {
|
||||
private static final String CONFIG_FILE = "db.properties";
|
||||
private static final String DEFAULT_DRIVER = "com.mysql.cj.jdbc.Driver";
|
||||
|
||||
@FunctionalInterface
|
||||
public interface TransactionCallback<T> {
|
||||
T execute(Connection connection) throws SQLException;
|
||||
}
|
||||
|
||||
private JdbcUtil() {
|
||||
}
|
||||
|
||||
@@ -31,6 +36,33 @@ public final class JdbcUtil {
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T executeInTransaction(TransactionCallback<T> callback) {
|
||||
try (Connection connection = getConnection()) {
|
||||
connection.setAutoCommit(false);
|
||||
try {
|
||||
T result = callback.execute(connection);
|
||||
connection.commit();
|
||||
return result;
|
||||
} catch (SQLException ex) {
|
||||
rollbackQuietly(connection);
|
||||
throw new DaoException("Unable to complete database transaction", ex);
|
||||
} catch (RuntimeException ex) {
|
||||
rollbackQuietly(connection);
|
||||
throw ex;
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
throw new DaoException("Unable to complete database transaction", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static void rollbackQuietly(Connection connection) {
|
||||
try {
|
||||
connection.rollback();
|
||||
} catch (SQLException ignored) {
|
||||
// Preserve the original transaction failure for callers and logs.
|
||||
}
|
||||
}
|
||||
|
||||
private static Properties loadProperties() {
|
||||
try (InputStream inputStream = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
|
||||
Reference in New Issue
Block a user