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

implemented CRUD operations #66

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
8 changes: 7 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@
https://raw.githubusercontent.com/mate-academy/style-guides/master/java/checkstyle.xml
</maven.checkstyle.plugin.configLocation>
</properties>

<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
Expand Down
30 changes: 30 additions & 0 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,37 @@
package mate.academy;

import java.math.BigDecimal;
import java.util.List;
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("Java to Wood People");
book.setPrice(BigDecimal.valueOf(350));

//Create
Book createdBook = bookDao.create(book);

//findById
Optional<Book> bookById = bookDao.findById(3L);
System.out.println(bookById);

//findAll
List<Book> allBooksFromDb = bookDao.findAll();

//update
book.setTitle("JDBC for wood people, Part2");
book.setPrice(BigDecimal.valueOf(500));
Book updatedBook = bookDao.update(book);

//delete
bookDao.deleteById(4L);
}
}
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 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 {
private static final int FIRST_PARAM = 1;
private static final int SECOND_PARAM = 2;
private static final int THIRD_PARAM = 3;
private static final long THIRD_ID = 3L;

@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(FIRST_PARAM, book.getTitle());
statement.setBigDecimal(SECOND_PARAM, book.getPrice());
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 create a new book: " + book, e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
String query = "SELECT * FROM books WHERE id = ?";
Book bookFromDb = null;
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setLong(FIRST_PARAM, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
bookFromDb = parseResultSetInBook(resultSet);
}
} catch (SQLException e) {
throw new DataProcessingException("Can not find Book with id: " + id, e);
}
return Optional.ofNullable(bookFromDb);
}

@Override
public List<Book> findAll() {
String query = "SELECT * FROM books";
List<Book> allBooksFromDb = new ArrayList<>();
try (Connection connection = ConnectionUtil.getConnection();
Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()) {
allBooksFromDb.add(parseResultSetInBook(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException("Can`t get all elements from DB.", e);
}
return allBooksFromDb;
}

@Override
public Book update(Book book) {
String query = "UPDATE books SET title = ?, price = ? WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(FIRST_PARAM, book.getTitle());
statement.setBigDecimal(SECOND_PARAM, book.getPrice());
statement.setLong(THIRD_PARAM, THIRD_ID);
statement.executeUpdate();
} catch (SQLException e) {
throw new DataProcessingException("Can not update book with id: " + book.getId(), e);
}
return book;
}

@Override
public boolean deleteById(Long id) {
String query = "DELETE FROM books WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setLong(FIRST_PARAM, id);
return statement.executeUpdate() > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can not delete book by the id: " + id, e);
}
}

private Book parseResultSetInBook(ResultSet resultSet) throws SQLException {
Book dbBook = new Book();
dbBook.setId(resultSet.getObject("id", Long.class));
dbBook.setTitle(resultSet.getString("title"));
dbBook.setPrice(resultSet.getBigDecimal("price"));
return dbBook;
}
}
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 ex) {
super(message, ex);
}
}
3 changes: 3 additions & 0 deletions src/main/java/mate/academy/lib/Dao.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package mate.academy.lib;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Dao {
}
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
+ '}';
}
}
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/books_db";
private static final Properties DB_PROPERTIES;

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

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

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL, DB_PROPERTIES);
}
}
11 changes: 11 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
CREATE database books_db;

USE books_db;

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

Loading