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

Create BookDao interface, MySqlBookDao class #49

Open
wants to merge 7 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
8 changes: 7 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
https://raw.githubusercontent.com/mate-academy/style-guides/master/java/checkstyle.xml
</maven.checkstyle.plugin.configLocation>
</properties>

<build>

Choose a reason for hiding this comment

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

Is it required to delete this?

<plugins>
<plugin>
Expand Down Expand Up @@ -56,4 +55,11 @@
</plugins>
</pluginManagement>
</build>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
52 changes: 52 additions & 0 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,59 @@
package mate.academy;

import java.math.BigDecimal;
import java.util.List;
import mate.academy.lib.Injector;
import mate.academy.model.Book;
import mate.academy.repository.BookDao;

public class Main {
private static final Injector INJECTOR = Injector.getInstance("mate.academy");
private static final List<Book> LIBRARY;

static {
Book book1 = new Book();
book1.setTitle("\"Flowers for Algernon\" Daniel Keyes");
book1.setPrice(BigDecimal.valueOf(8));

Book book2 = new Book();
book2.setTitle("\"Shining\" Stephen King");
book2.setPrice(BigDecimal.valueOf(13));

Book book3 = new Book();
book3.setTitle("\"Fight Club\" Chuck Palahniuk");
book3.setPrice(BigDecimal.valueOf(20));

LIBRARY = List.of(book1, book2, book3);
}

public static void main(String[] args) {
//Get BookDao instance using Injector
BookDao bookDao = (BookDao) INJECTOR.getInstance(BookDao.class);

//Create new books in the database
LIBRARY.forEach(bookDao::create);

//Read all books from the database and compare it with library list
List<Book> booksFromDB = bookDao.findAll();
System.out.println("Books from database:");
booksFromDB.forEach(System.out::println);

//Find by id
Book bookFromLib = LIBRARY.get(0);
Book bookFromDb = bookDao.findById(bookFromLib.getId()).orElseThrow();
System.out.println("Book from db: " + bookFromDb + System.lineSeparator());

//Update
bookFromLib.setTitle("Updated title");
bookDao.update(bookFromLib);
bookFromDb = bookDao.findById(bookFromLib.getId()).orElseThrow();
System.out.println("Expect that title is updated: "
+ bookFromDb + System.lineSeparator());

//Delete by id
bookDao.deleteById(bookFromLib.getId());

//Delete all books in the database
LIBRARY.forEach(book -> bookDao.deleteById(book.getId()));
}
}
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) {
super(message);
}

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

import java.math.BigDecimal;

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

public Long getId() {
return id;
}

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

public String getTitle() {
return title;
}

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

public BigDecimal getPrice() {
return price;
}

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

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

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);
}
119 changes: 119 additions & 0 deletions src/main/java/mate/academy/repository/MySqlBookDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package mate.academy.repository;

import java.math.BigDecimal;
import java.sql.Connection;
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;

@Dao
public class MySqlBookDao implements BookDao {
private static final int ID_PARAMETER_INDEX = 1;
private static final int TITLE_PARAMETER_INDEX = 1;
private static final int PRICE_PARAMETER_INDEX = 2;
private static final int UPDATE_ID_PARAMETER_INDEX = 3;
private static final int ZERO_AFFECTED_ROW = 0;
private static final String ID_ROW_LABEL = "id";
private static final String TITLE_ROW_LABEL = "title";
private static final String PRICE_ROW_LABEL = "price";

@Override
public Book create(Book book) {
String query = "INSERT INTO book(title, price) VALUES(?, ?)";
try (Connection connection = MySqlConnectionManager.getConnection();
PreparedStatement statement = connection
.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(TITLE_PARAMETER_INDEX, book.getTitle());
statement.setBigDecimal(PRICE_PARAMETER_INDEX, book.getPrice());
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
book.setId(generatedKeys.getLong(1));
}
} catch (SQLException e) {
throw new DataProcessingException(
"Cannot create new book, something gone wrong: " + book, e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
String query = "SELECT * FROM book WHERE id = ?";
try (Connection connection = MySqlConnectionManager.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setLong(ID_PARAMETER_INDEX, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
Book book = parseToObject(resultSet);
return Optional.of(book);
}
} catch (SQLException e) {
throw new DataProcessingException(
"Can't get Book from database by id " + id, e);
}
return Optional.empty();
}

@Override
public List<Book> findAll() {
String query = "SELECT * FROM book";
List<Book> resultList = new ArrayList<>();
try (Connection connection = MySqlConnectionManager.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Book book = parseToObject(resultSet);
resultList.add(book);
}
} catch (SQLException e) {
throw new DataProcessingException("Cannot get books from database", e);
}
return resultList;
}

@Override
public Book update(Book book) {
String query = "UPDATE book SET title= ?, price= ? WHERE id = ?";
try (Connection connection = MySqlConnectionManager.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(TITLE_PARAMETER_INDEX, book.getTitle());
statement.setBigDecimal(PRICE_PARAMETER_INDEX, book.getPrice());
statement.setLong(UPDATE_ID_PARAMETER_INDEX, book.getId());

Choose a reason for hiding this comment

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

Where is executeUpdate() call?

statement.executeUpdate();
} catch (SQLException e) {
throw new DataProcessingException("Book was not updated: " + book, e);
}
return book;
}

@Override
public boolean deleteById(Long id) {
String query = "DELETE FROM book WHERE id =?";
try (Connection connection = MySqlConnectionManager.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setLong(ID_PARAMETER_INDEX, id);
return statement.executeUpdate() > ZERO_AFFECTED_ROW;
} catch (SQLException e) {
throw new DataProcessingException("Cannot delete book by id " + id, e);
}
}

private Book parseToObject(ResultSet resultSet) throws SQLException {
Long id = resultSet.getObject(ID_ROW_LABEL, Long.class);
String title = resultSet.getString(TITLE_ROW_LABEL);
BigDecimal price = resultSet.getBigDecimal(PRICE_ROW_LABEL);
Book book = new Book();
book.setId(id);
book.setTitle(title);
book.setPrice(price);
return book;
}
}
27 changes: 27 additions & 0 deletions src/main/java/mate/academy/repository/MySqlConnectionManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package mate.academy.repository;

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

public class MySqlConnectionManager {
private static final String DB_URL = "jdbc:mysql://localhost:3306/library";
private static final Properties DB_PROPERTIES;

static {
DB_PROPERTIES = new Properties();
DB_PROPERTIES.put("user", "test");
DB_PROPERTIES.put("password", "StrongSecret1234");

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

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL, DB_PROPERTIES);
}
}
7 changes: 7 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CREATE SCHEMA library;
USE library;
CREATE TABLE book (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
price DECIMAL NOT NULL
)
Loading