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 solution to the task: #11

Closed
Closed
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: 8 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,12 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
</dependencies>

</project>
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 mate.academy.dao.BookDao;
import mate.academy.lib.Injector;
import mate.academy.model.Book;
import java.math.BigDecimal;

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

public static void main(String[] args) {
Book theTimeBook = new Book();
theTimeBook.setId(1L);
theTimeBook.setTitle("The time");
theTimeBook.setPrice(BigDecimal.valueOf(80));
Book myWarBook = new Book(3L, "My war", BigDecimal.valueOf(130));

BookDao bookDao = (BookDao) injector.getInstance(BookDao.class);
System.out.println(bookDao.create(myWarBook));
System.out.println(bookDao.findById(1L).get());
System.out.println(bookDao.findAll());
System.out.println(bookDao.update(theTimeBook));
System.out.println(bookDao.deleteById(2L));
}
}
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);
}
109 changes: 109 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package mate.academy.dao;

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

@Dao
public class BookDaoImpl implements BookDao {
@Override
public Book create(Book book) {
String query = "INSERT INTO books (title, price) VALUES(?, ?)";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query,
Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());

int affectedRows = statement.executeUpdate();
if (affectedRows < 1) {
throw new RuntimeException("Expected to insert at"
+ " least one row, but inserted 0 rows");
}

ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
Long id = generatedKeys.getObject(1, Long.class);
book.setId(id);
}
} catch (SQLException e) {
throw new DataProcessingException("Can't insert book " + book + "to DB", e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
String query = "SELECT * FROM books WHERE id = ? AND is_deleted = FALSE";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setLong(1, id);
ResultSet resultSet = statement.executeQuery();

Book book = new Book();
if (resultSet.next()) {
book = getBook(resultSet);
}
return Optional.ofNullable(book);
} catch (SQLException e) {
throw new DataProcessingException("Can't get book by id " + id, e);
}
}

@Override
public List<Book> findAll() {
String query = "SELECT * FROM books WHERE is_deleted = FALSE";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
List<Book> books = new ArrayList<>();
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
books.add(getBook(resultSet));
}
return books;
} catch (SQLException e) {
throw new DataProcessingException("Can't find any book", e);
}
}

@Override
public Book update(Book book) {
String query = "UPDATE books SET title = ?, price = ? " +
"WHERE id = ? AND is_deleted = FALSE";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
statement.setLong(3, book.getId());
statement.executeUpdate();
return book;
} catch (SQLException e) {
throw new DataProcessingException("Can't update book " + book, e);
}
}

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

private Book getBook(ResultSet resultSet) throws SQLException {
Long id = resultSet.getObject("id", Long.class);
String title = resultSet.getString("title");
BigDecimal price = resultSet.getBigDecimal("price");
return new Book(id, title, price);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package mate.academy.exception;

public class DataProcessingException extends RuntimeException {
public DataProcessingException(String message, Throwable cause) {
super(message, cause);
}
}
56 changes: 56 additions & 0 deletions src/main/java/mate/academy/model/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
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 Book() {
}

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

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

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
+ '}';
}
}
28 changes: 28 additions & 0 deletions src/main/java/mate/academy/util/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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 URL = "jdbc:mysql://localhost:3306/book_db";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456789";
private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";

static {
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Can't find SQL Driver", e);
}
}

public static Connection getConnection() throws SQLException {
Properties dbProperties = new Properties();
dbProperties.setProperty("user", USERNAME);
dbProperties.setProperty("password", PASSWORD);
return DriverManager.getConnection(URL, dbProperties);
}
}
10 changes: 10 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE SCHEMA IF NOT EXISTS `book_db` DEFAULT CHARACTER SET utf8;
USE `book_db`;

CREATE TABLE `books` (
`id` int NOT NULL AUTO_INCREMENT,
`title` varchar(200) DEFAULT NULL,
`price` decimal(10,0) DEFAULT NULL,
`is_deleted` tinyint DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
Loading