체스 미션에서는 데이터베이스에서 값을 가져오기 위해 DAO를 사용했다.
이 때 JDBC를 사용할 때 데이터베이스의 커넥션을 얻고, try-with-resource를 사용하는 부분이 반복되었다.
템플릿 콜백 패턴을 이용하여 나만의 JdbcTemplate을 만들어보았다.
기존 코드
- User
- UserDao
- ConnectionPool
public class User {
private final int id;
private final String name;
public User(final int id, final String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
public class UserDao {
private final ConnectionPool connectionPool;
public UserDao(final ConnectionPool connectionPool) {
this.connectionPool = connectionPool;
}
public void insert(final String name) {
final Connection connection = connectionPool.getConnection();
final String query = "INSERT INTO User (name) VALUES (?)";
try (final PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, name);
preparedStatement.executeUpdate();
} catch (final SQLException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
public void delete(final int userId) {
final Connection connection = connectionPool.getConnection();
final String query = "DELETE FROM user WHERE id = ?";
try (final PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setInt(1, userId);
preparedStatement.executeUpdate();
} catch (final SQLException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
public User findById(final int userId) {
final Connection connection = connectionPool.getConnection();
final String query = "SELECT * FROM user WHERE id = ?";
try (final PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setInt(1, userId);
final ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return new User(
resultSet.getInt("id"),
resultSet.getString("name")
);
}
} catch (final SQLException e) {
throw new IllegalArgumentException(e.getMessage());
}
return null;
}
public List<User> findAll() {
final Connection connection = connectionPool.getConnection();
final String query = "SELECT * FROM user";
try (final PreparedStatement preparedStatement = connection.prepareStatement(query)) {
final ResultSet resultSet = preparedStatement.executeQuery();
final List<User> result = new ArrayList<>();
while (resultSet.next()) {
result.add(new User(
resultSet.getInt("id"),
resultSet.getString("name")
));
}
return result;
} catch (final SQLException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}