Skip to content

Commit

Permalink
Added parseBook method to BookDaoImpl class
Browse files Browse the repository at this point in the history
  • Loading branch information
igor031299 committed Jul 27, 2024
1 parent a80408b commit 3ec73a8
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 18 deletions.
28 changes: 12 additions & 16 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ public Book create(Book book) {
statement.setObject(2, book.getPrice());
int affectedRows = statement.executeUpdate();
if (affectedRows < 1) {
throw new RuntimeException("Can't create book in db");
throw new DataProcessingException(
"Expected to insert at least 1 row, but 0 was inserted");
}
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
Expand All @@ -51,13 +52,7 @@ public Optional<Book> findById(Long id) {
statement.setLong(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String title = resultSet.getString("title");
BigDecimal price = resultSet.getObject("price", BigDecimal.class);

Book book = new Book();
book.setId(id);
book.setTitle(title);
book.setPrice(price);
Book book = parseBook(resultSet);
return Optional.of(book);
}
} catch (SQLException e) {
Expand All @@ -72,15 +67,8 @@ public List<Book> findAll() {
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_FIND_ALL);
ResultSet resultSet = statement.executeQuery()) {

while (resultSet.next()) {
Long id = resultSet.getLong(1);
String title = resultSet.getString(2);
BigDecimal price = resultSet.getBigDecimal(3);
Book book = new Book();
book.setId(id);
book.setTitle(title);
book.setPrice(price);
Book book = parseBook(resultSet);
result.add(book);
}
} catch (SQLException e) {
Expand Down Expand Up @@ -118,4 +106,12 @@ public boolean deleteById(Long id) {
throw new DataProcessingException("Can't delete book from db by id " + id, e);
}
}

private static Book parseBook(ResultSet resultSet) throws SQLException {
Book book = new Book();
book.setTitle(resultSet.getString("title"));
book.setId(resultSet.getObject("id", Long.class));
book.setPrice(resultSet.getObject("price", BigDecimal.class));
return book;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@ public class DataProcessingException extends RuntimeException {
public DataProcessingException(String message, Throwable ex) {
super(message, ex);
}

public DataProcessingException(String message) {
super(message);
}
}
3 changes: 1 addition & 2 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
USE test;
DROP TABLE IF EXISTS book;
DROP IF EXISTS book;
CREATE TABLE book (
id BIGINT AUTO_INCREMENT,
title VARCHAR(100) NOT NULL,
Expand Down

0 comments on commit 3ec73a8

Please sign in to comment.