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

established connection to DB, created Book entity class and BookDao i… #340

Open
wants to merge 1 commit 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
9 changes: 9 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
</maven.checkstyle.plugin.configLocation>
</properties>

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

</dependencies>

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

import java.math.BigDecimal;
import java.util.Optional;
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();
book.setTitle("Sherlock Holmes");
book.setPrice(BigDecimal.valueOf(110L));

Book savedBook = bookDao.create(book);
Optional<Book> bookById = bookDao.findById(savedBook.getId());
System.out.println(bookById);
System.out.println(bookDao.findAll());

book.setPrice(BigDecimal.valueOf(371L));
bookDao.update(book);
bookDao.findById(savedBook.getId());
bookDao.deleteById(savedBook.getId());
System.out.println(bookDao.findAll());
}
}
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);
}
129 changes: 129 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package mate.academy.dao;

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;
import mate.academy.util.ConnectionUtil;

@Dao
public class BookDaoImpl implements BookDao {

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

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

ResultSet generatedKeys = createObjectStatement.getGeneratedKeys();
if (generatedKeys.next()) {
book.setId(generatedKeys.getLong(1));
}

} catch (SQLException e) {
throw new DataProcessingException("Can`t insert book "
+ book + " to DB", e);
}
return book;
}

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

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

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
String getAllRequest = "SELECT * FROM books";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement getAllBooksStatement
= connection.prepareStatement(getAllRequest)) {
ResultSet resultSet = getAllBooksStatement.executeQuery();

while (resultSet.next()) {
Book book = createBook(resultSet);
books.add(book);
}

} catch (SQLException e) {
throw new DataProcessingException("Can`t get all books from DB", e);
}
return books;
}

@Override
public Book update(Book book) {
String updateRequest = "UPDATE books SET title = ?, price = ? WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement updateBookStatement
= connection.prepareStatement(updateRequest)) {
updateBookStatement.setString(1, book.getTitle());
updateBookStatement.setBigDecimal(2, book.getPrice());
updateBookStatement.setString(3, String.valueOf(book.getId()));
updateBookStatement.executeUpdate();
} catch (SQLException e) {
throw new DataProcessingException("Can`t update book "
+ book + " from DB", e);
}
return book;
}

@Override
public boolean deleteById(Long id) {
String deleteRequest = "DELETE FROM books WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement deletedStatement
= connection.prepareStatement(deleteRequest)) {
deletedStatement.setLong(1, id);
int rowsAffected = deletedStatement.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can`t delete book by id "
+ id + " from DB", e);
}
}

private static Book createBook(ResultSet resultSet) throws SQLException {
Long id = resultSet.getObject("id", Long.class);
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);
return book;
}
}
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);
}
}
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
+ '}';
}
}
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 DB_URL = "jdbc:mysql://localhost:3306/test";

private static final Properties DB_PROPERTIES;

static {
DB_PROPERTIES = new Properties();
DB_PROPERTIES.put("user", "root");
DB_PROPERTIES.put("password", "202-42HP");

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

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

Choose a reason for hiding this comment

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

Suggested change
);
);

Loading