17 트랜잭션
@Data
public class Account {
private String name;
private int amount;
}
public class AccountRepository {
// 잔액 조회 메서드
public Account findByName(Connection connection, String name) throws SQLException {
String sql = "SELECT name, amount FROM Account WHERE name = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, name);
ResultSet rs = null;
try {
rs = pstmt.executeQuery();
if (rs.next()) {
Account account = new Account();
account.setName(rs.getString("name"));
account.setAmount(rs.getInt("amount"));
return account;
} else {
throw new RuntimeException("Account not found: " + name);
}
} finally {
if (rs != null) {
rs.close();
}
pstmt.close();
}
}
// 출금 메서드
public void withdraw(Connection connection, String name, int amount) throws SQLException {
Account account = findByName(connection, name);
if (account.getAmount() < amount) {
throw new RuntimeException("Insufficient balance");
}
String sql = "UPDATE Account SET amount = amount - ? WHERE name = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
try {
pstmt.setInt(1, amount);
pstmt.setString(2, name);
pstmt.executeUpdate();
} finally {
pstmt.close();
}
}
// 입금 메서드
public void deposit(Connection connection, String name, int amount) throws SQLException {
String sql = "UPDATE Account SET amount = amount + ? WHERE name = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
try {
pstmt.setInt(1, amount);
pstmt.setString(2, name);
pstmt.executeUpdate();
} finally {
pstmt.close();
}
}
// 계좌 생성 메서드
public void createAccount(Connection connection, String name, int amount) throws SQLException {
String sql = "INSERT INTO Account (name, amount) VALUES (?, ?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
try {
pstmt.setString(1, name);
pstmt.setInt(2, amount);
pstmt.executeUpdate();
} finally {
pstmt.close();
}
}
// 계좌 삭제 메서드
public void deleteAccount(Connection connection, String name) throws SQLException {
String sql = "DELETE FROM Account WHERE name = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
try {
pstmt.setString(1, name);
pstmt.executeUpdate();
} finally {
pstmt.close();
}
}
}Last updated