Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added task solution #408

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@
https://raw.githubusercontent.com/mate-academy/style-guides/master/java/checkstyle.xml
</maven.checkstyle.plugin.configLocation>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>

<build>
<plugins>
Expand Down
18 changes: 18 additions & 0 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
package mate.academy;

import java.math.BigDecimal;
import mate.academy.dao.BookDao;
import mate.academy.lib.Injector;
import mate.academy.model.Book;

public class Main {
private static final Injector injector = Injector.getInstance("mate.academy");

public static void main(String[] args) {
BookDao bookDao = (BookDao) injector.getInstance(BookDao.class);
Book book = new Book(1L, "Java Programming", new BigDecimal(200));

bookDao.create(book);
bookDao.findAll().forEach(System.out::println);
System.out.println();
System.out.println("Id 1 " + System.lineSeparator() + bookDao.findById(1L));
bookDao.deleteById(2L);
bookDao.findAll().forEach(System.out::println);
System.out.println();
bookDao.update(book);
bookDao.findAll().forEach(System.out::println);
}
}
17 changes: 17 additions & 0 deletions src/main/java/mate/academy/dao/BookDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package mate.academy.dao;

import java.util.List;
import java.util.Optional;
import mate.academy.model.Book;

public interface BookDao {
Book create(Book book);

Optional<Book> findById(Long id);

List<Book> findAll();

Book update(Book book);

boolean deleteById(Long id);
}
120 changes: 120 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package mate.academy.dao;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import mate.academy.exception.DataProcessingException;
import mate.academy.lib.Dao;
import mate.academy.model.Book;
import mate.academy.util.ConnectionUtil;

@Dao
public class BookDaoImpl implements BookDao {

@Override
public Book create(Book book) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add Override annotation (check all methods)

String sql = "INSERT INTO books (title, price) VALUES (?, ?)";

try (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement(sql,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should close the PreparedStatement explicitly after use. The try-with-resources statement is already doing that, but it's a good practice to close it explicitly if you're going to reuse the connection.

Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());

int affectedRows = statement.executeUpdate();

if (affectedRows < 1) {
throw new DataProcessingException("Creating book failed, no rows affected.");
}

try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
book.setId(generatedKeys.getObject(1, Long.class));
} else {
throw new DataProcessingException("Creating book failed, no ID obtained.");
}
}
} catch (SQLException e) {
throw new DataProcessingException("Can't create book " + book, e);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The exception message is good, it's informative and includes the book that failed to be created.

}

return book;
}

@Override
public Optional<Book> findById(Long id) {
String sql = "SELECT * FROM books WHERE id = ?";

try (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement(sql)) {
statement.setLong(1, id);

try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return Optional.of(getBook(resultSet));
}
}
} catch (SQLException e) {
throw new DataProcessingException("Can't find by id for id = " + id, e);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The exception message is good, it's informative and includes the id that was not found.

}

return Optional.empty();
}

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
String sql = "SELECT * FROM books";

try (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement(sql);
ResultSet resultSet = statement.executeQuery()) {

while (resultSet.next()) {
books.add(getBook(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't retrieve all books", e);
}

return books;
}

@Override
public Book update(Book book) {
String sql = "UPDATE books SET price = ?, title = ? WHERE id = ?";
try (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement(sql)) {
statement.setBigDecimal(1, book.getPrice());
statement.setString(2, book.getTitle());
statement.setLong(3, book.getId());
if (statement.executeUpdate() > 0) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The update method should not throw an exception if no book is found with the given id; it should simply return the unmodified book or use a different way to indicate that no update was performed.

return book;
} else {
throw new DataProcessingException("No book found with id = " + book.getId(),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid throwing a generic RuntimeException. Instead, use the SQLException that is caught in the catch block to maintain the stack trace and cause of the original exception.

new RuntimeException());
}
} catch (SQLException e) {
throw new DataProcessingException("Can't update book with id = " + book.getId(), e);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The exception message is good, it's informative and includes the id of the book that failed to update.

}
}
Comment on lines +86 to +101

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the update method, save the query in a separate variable before the try block to maintain consistency and readability. Also, ensure to close the PreparedStatement explicitly after use.


@Override
public boolean deleteById(Long id) {
String sql = "DELETE FROM books WHERE id = ?";
try (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement(sql)) {
statement.setLong(1, id);
return statement.executeUpdate() > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can't delete book with id = " + id, e);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The exception message is good, it's informative and includes the id of the book that failed to be deleted.

}
}

private Book getBook(ResultSet resultSet) throws SQLException {
Long id = resultSet.getObject("id", Long.class);
BigDecimal price = resultSet.getObject("price", BigDecimal.class);
String title = resultSet.getString("title");
return new Book(id, title, price);
}
}
11 changes: 11 additions & 0 deletions src/main/java/mate/academy/exception/DataProcessingException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.exception;

public class DataProcessingException extends RuntimeException {
public DataProcessingException(String message, Throwable ex) {
super(message, ex);
}

public DataProcessingException(String message) {
super(message);
}
}
48 changes: 48 additions & 0 deletions src/main/java/mate/academy/model/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package mate.academy.model;

import java.math.BigDecimal;

public class Book {
private Long id;
private String title;
private BigDecimal price;

public Book(Long id, String title, BigDecimal price) {
this.id = id;
this.title = title;
this.price = price;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public BigDecimal getPrice() {
return price;
}

public void setPrice(BigDecimal price) {
this.price = price;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

@Override
public String toString() {
return "Book{"
+ "id = " + id
+ " title = " + title
+ " price = " + price
+ '}';
}
}
27 changes: 27 additions & 0 deletions src/main/java/mate/academy/util/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package mate.academy.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionUtil {
private static final String DB_URL = "jdbc:mysql://localhost:3306/bookstore";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The DB_URL is not complete. It should contain the full JDBC URL, including the database name and other required parameters for the connection.

private static final Properties DB_PROPERTIES;

static {
DB_PROPERTIES = new Properties();
DB_PROPERTIES.put("user", "root");
DB_PROPERTIES.put("password", "qwertyasd");

try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Can not load JDBC", e);
}
}

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL, DB_PROPERTIES);
}
}
16 changes: 16 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
CREATE DATABASE IF NOT EXISTS BookStore DEFAULT CHARACTER SET utf8;

USE BookStore;

CREATE TABLE Books (
id BIGINT AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
PRIMARY KEY (id)
);

INSERT INTO Books (title, price) VALUES ('The Great Gatsby', 10.99);
INSERT INTO Books (title, price) VALUES ('1984', 8.99);
INSERT INTO Books (title, price) VALUES ('To Kill a Mockingbird', 12.50);
INSERT INTO Books (title, price) VALUES ('Pride and Prejudice', 9.75);
INSERT INTO Books (title, price) VALUES ('The Catcher in the Rye', 11.20);
Loading