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

Jbdc #384

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open

Jbdc #384

Show file tree
Hide file tree
Changes from 5 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
24 changes: 23 additions & 1 deletion src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
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 {
public static void main(String[] args) {
private static Injector injector = Injector.getInstance("mate.academy");

Choose a reason for hiding this comment

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

Suggested change
private static Injector injector = Injector.getInstance("mate.academy");
private static final Injector injector = Injector.getInstance("mate.academy");


public static void main(String[] args) {
Book harryPotter = new Book();
harryPotter.setTitle("Harry Potter");
harryPotter.setPrice(BigDecimal.valueOf(25));
Book lordOfTheRings = new Book();
lordOfTheRings.setTitle("Lord of the Rings");
lordOfTheRings.setPrice(BigDecimal.valueOf(15));
BookDao bookDao = (BookDao) injector.getInstance(BookDao.class);
Book harryPotterBook = bookDao.create(harryPotter);
Book lotrBook = bookDao.create(lordOfTheRings);
System.out.println(harryPotterBook);
System.out.println(lotrBook);
bookDao.findAll().forEach(System.out::println);
harryPotter.setPrice(BigDecimal.valueOf(50));
bookDao.update(harryPotter);
bookDao.deleteById(1L);
bookDao.findById(2L).ifPresent(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);
}
114 changes: 114 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
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 sql = "INSERT INTO books (title, price) VALUES (?, ?);";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement preparedStatement
= connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
preparedStatement.setString(1, book.getTitle());
preparedStatement.setString(2, book.getPrice().toString());
preparedStatement.executeUpdate();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()) {
Long id = resultSet.getObject(1, Long.class);
book.setId(id);
}
return book;
} catch (SQLException e) {
throw new DataProcessingException("Can not create book" + book, e);
}
}

@Override
public Optional<Book> findById(Long id) {
String sql = "SELECT * FROM books WHERE id = ?;";
Book book;
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement preparedStatement
= connection.prepareStatement(sql)) {
preparedStatement.setLong(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
book = getBook(resultSet);
return Optional.of(book);
}
} catch (SQLException e) {
throw new DataProcessingException("Can ot find book by id" + id, e);

Choose a reason for hiding this comment

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

Suggested change
throw new DataProcessingException("Can ot find book by id" + id, e);
throw new DataProcessingException("Can not find book by id" + id, e);

}
return Optional.empty();
}

@Override
public List<Book> findAll() {
String sql = "SELECT * FROM books;";
List<Book> books = new ArrayList<>();
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement preparedStatement
= connection.prepareStatement(sql)) {
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
books.add(getBook(resultSet));
}
return books;
} catch (SQLException e) {
throw new DataProcessingException("Can not find books from db", e);
}
}

@Override
public Book update(Book book) {
String sql = "UPDATE books SET title = ?, price = ? WHERE id = ?;";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement preparedStatement
= connection.prepareStatement(sql)) {
preparedStatement.setString(1, book.getTitle());
preparedStatement.setString(2, book.getPrice().toString());
preparedStatement.setLong(3, book.getId());
preparedStatement.executeUpdate();
return book;
} catch (SQLException e) {
throw new DataProcessingException("Can not update book from db" + book, e);
}
}

@Override
public boolean deleteById(Long id) {
String sql = "DELETE FROM books WHERE id = ?;";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement preparedStatement
= connection.prepareStatement(sql)) {
preparedStatement.setLong(1, id);
return preparedStatement.executeUpdate() > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can not delete by id from db" + 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");
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 e) {
super(message, e);
}
}
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
+ '}';
}
}
32 changes: 32 additions & 0 deletions src/main/java/mate/academy/util/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package mate.academy.util;

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

public class ConnectionUtil {
public static final String SQL_DRIVER = "com.mysql.cj.jdbc.Driver";
public static final String DB_URL = "jdbc:mysql://localhost:3306/books_db";
public static final String USER = "root";
public static final String PASSWORD = "!Vladius080197";

static {
try {
Class.forName(SQL_DRIVER);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Can not load JDBC driver.", e);
}
}

public static Connection getConnection() {
try {
Properties properties = new Properties();
properties.setProperty("user", USER);
properties.setProperty("password", PASSWORD);
return DriverManager.getConnection(DB_URL, properties);
} catch (SQLException e) {
throw new RuntimeException("Can not create connection to database", e);
}
}
}
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 DATABASE 'books_db';

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