本の返却
あなたは大都市公共図書館の管理システムを開発しているエンジニアです。先週、重大なバグが発見されました。本の返却処理中にシステムがクラッシュした際、貸出記録は「返却済み」に更新されたにもかかわらず、在庫上の本のステータスは「貸出中」のままになっていました。その結果、スタッフがデータベースを手動で修正するまで、その本は数週間にわたって利用できない状態が続きました。
本が返却される際、次の 3 つの操作はすべて成功するか、すべて失敗するかのどちらかでなければなりません。
- 貸出記録のステータスを「返却済み」に更新する。
- 本の在庫状況を「貸出中」から「利用可能」に変更する。
- 本が返却期限を過ぎている場合、延滞料金を記録する。
データの整合性を確保するために、適切なトランザクション制御を実装しましょう。
この演習はコースの一部です
Java で PostgreSQL データベースにクエリを実行する
演習の手順
- 26 行目で
autoCommitをfalseに設定します。 - 59 行目で、すべての操作が成功した場合にトランザクションをコミットします。
- 66 行目で、いずれかの操作が失敗した場合にトランザクションをロールバックします。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
public class BookReturnProcessor {
public static void main(String[] args) {
int loanId = 1;
int bookId = 5;
LocalDate dueDate = LocalDate.now().minusDays(2);
try {
boolean success = processBookReturn(loanId, bookId, dueDate);
if (success) {
System.out.println("Book return processed successfully.");
} else {
System.out.println("Book return processing failed.");
}
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
public static boolean processBookReturn(int loanId, int bookId, LocalDate dueDate) throws SQLException {
Connection conn = null;
try {
HikariDataSource ds = HikariSetup.createDataSource();
conn = ds.getConnection();
// Start transaction by setting autoCommit to false
conn.____(____);
String updateLoanSQL = "UPDATE loans SET status = 'returned', return_date = ? WHERE loan_id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(updateLoanSQL)) {
pstmt.setDate(1, java.sql.Date.valueOf(LocalDate.now()));
pstmt.setInt(2, loanId);
pstmt.executeUpdate();
}
String updateBookSQL = "UPDATE books SET status = 'available' WHERE book_id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(updateBookSQL)) {
pstmt.setInt(1, bookId);
pstmt.executeUpdate();
}
LocalDate today = LocalDate.now();
if (today.isAfter(dueDate)) {
long daysLate = ChronoUnit.DAYS.between(dueDate, today);
double fineAmount = daysLate * 0.50;
String insertFineSQL = "INSERT INTO fines (loan_id, amount, reason, date_assessed) VALUES (?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertFineSQL)) {
pstmt.setInt(1, loanId);
pstmt.setDouble(2, fineAmount);
pstmt.setString(3, "Book returned " + daysLate + " days late");
pstmt.setDate(4, java.sql.Date.valueOf(today));
pstmt.executeUpdate();
}
System.out.println("Fine created: $" + fineAmount + " for loan " + loanId);
}
// Commit the transaction
conn.____();
return true;
} catch (SQLException e) {
// Roll back the transaction if an error occurs
if (conn != null) {
conn.____();
}
System.err.println("Error processing return: " + e.getMessage());
return false;
}
}
}