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

resolve jdbc-intro #356

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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 @@ -18,6 +18,14 @@
</maven.checkstyle.plugin.configLocation>
</properties>

<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>

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

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import mate.academy.exception.DataProcessingException;

public class ConnectionUtil {

Choose a reason for hiding this comment

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

it's better to create util package and replace it there

private static final String URL = "jdbc:mysql://localhost:3306/book_db";
private static final Properties PROPERTIES;

static {
PROPERTIES = new Properties();
PROPERTIES.put("user", "root");
PROPERTIES.put("password", "rootroot");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new DataProcessingException("Can not load JDBC driver", e);
}
}

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, PROPERTIES);
}
}
55 changes: 55 additions & 0 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,62 @@
package mate.academy;

import java.math.BigDecimal;
import mate.academy.dao.BookDao;
import mate.academy.lib.Injector;
import mate.academy.model.Book;
import mate.academy.service.BookService;
import mate.academy.service.BookServiceImpl;

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

public static void main(String[] args) {
BookDao bookDao = (BookDao) injector.getInstance(BookDao.class);
service = new BookServiceImpl(bookDao);

testCreate();

Choose a reason for hiding this comment

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

rename methods or don't create separate methods

testFindAll();
testFindById();
testUpdate();
testDelete();
testFindAll();

service.deleteAll();
}

private static void testCreate() {
System.out.println("\nCREATE");
Book bookHarry = new Book("Harry", new BigDecimal(1222));

Choose a reason for hiding this comment

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

Let's create List books = List.of(new Book(.... and use it in books.stream().map(...

Book bookPotter = new Book("Potter", new BigDecimal(999));
Book bookLol = new Book("Lol", new BigDecimal(69));
Book bookKek = new Book("Kek", new BigDecimal(1488));
service.createBook(bookHarry);
service.createBook(bookPotter);
service.createBook(bookLol);
service.createBook(bookKek);
}

private static void testFindAll() {
System.out.println("\nFIND ALL");
for (var book : service.findAllBooks()) {

Choose a reason for hiding this comment

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

service.findAllBooks().stream().forEach(System.out::println);

System.out.println(book);
}
}

private static void testFindById() {
System.out.println("\nFIND BY ID");
System.out.println(service.findBookById(3L));
}

private static void testDelete() {
System.out.println("\nDELETE");
service.deleteBookById(4L);
}

private static void testUpdate() {
System.out.println("\nUPDATE");
Book bookForUpdate = new Book(3L, "Update", new BigDecimal(12345));
service.updateBook(bookForUpdate);
}
}
19 changes: 19 additions & 0 deletions src/main/java/mate/academy/dao/BookDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
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);

boolean deleteAll();
}
139 changes: 139 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
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.ConnectionUtil;
import mate.academy.exception.DataProcessingException;
import mate.academy.lib.Dao;
import mate.academy.model.Book;

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

statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());

int affectedRows = statement.executeUpdate();
if (affectedRows < 1) {
throw new DataProcessingException("expected insert at least 1 row, but was 0.",
new RuntimeException());
}

ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
Long id = generatedKeys.getObject(1, Long.class);
book.setId(id);
}
} catch (SQLException e) {
throw new DataProcessingException("can not add new book: " + book, e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
String sql = "SELECT * FROM book_db.books WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {

statement.setLong(1, id);
ResultSet resultSet = statement.executeQuery();

if (resultSet.next()) {
return Optional.of(mapToBook(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException("can not find book by id : " + id, e);
}
return Optional.empty();
}

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

while (resultSet.next()) {
books.add(mapToBook(resultSet));
}

return books;
} catch (SQLException e) {
throw new DataProcessingException("Can not find all books", e);
}
}

@Override
public Book update(Book book) {
String sql = "UPDATE book_db.books SET title = ?, price = ? WHERE id = ?";

try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {

statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
statement.setLong(3, book.getId());

int rowsAffected = statement.executeUpdate();

Choose a reason for hiding this comment

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

Suggested change
int rowsAffected = statement.executeUpdate();
if (affectedRows < 1) {.....

Copy link

Choose a reason for hiding this comment

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

not fixed, throw exception in this situation, please don't ignore comments - if you disagree or don't understand them, ask in chat on the platform

System.out.println("Rows updated: " + rowsAffected);
Copy link

Choose a reason for hiding this comment

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

remove this

return book;
} catch (SQLException e) {
throw new DataProcessingException("Can not find all books", e);

Choose a reason for hiding this comment

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

wrong message

}
}

@Override
public boolean deleteById(Long id) {
String sql = "DELETE FROM book_db.books WHERE id = ?";

try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {

statement.setLong(1, id);

int rowsAffected = statement.executeUpdate();

Choose a reason for hiding this comment

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

Suggested change
int rowsAffected = statement.executeUpdate();
return statement.executeUpdate() > 0;

System.out.println("Rows deleted: " + rowsAffected);
return rowsAffected > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can not find all books", e);

Choose a reason for hiding this comment

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

the same

}
}

@Override
public boolean deleteAll() {
String sql = "DELETE FROM book_db.books";

try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {

int rowsAffected = statement.executeUpdate();

Choose a reason for hiding this comment

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

the same

System.out.println("Deleted " + rowsAffected + " rows from table books");
return rowsAffected > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can not delete all books", e);

Choose a reason for hiding this comment

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

the same

}
}

private Book mapToBook(ResultSet resultSet) throws SQLException {
Long id = resultSet.getObject("id", Long.class);
String title = resultSet.getString("title");
BigDecimal price = resultSet.getObject("price", BigDecimal.class);
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 ex) {
super(message, ex);
}
}
54 changes: 54 additions & 0 deletions src/main/java/mate/academy/model/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package mate.academy.model;

import java.math.BigDecimal;

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

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

public Book(String title, BigDecimal price) {
this.title = title;
this.price = 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
+ '}';
}
}

19 changes: 19 additions & 0 deletions src/main/java/mate/academy/service/BookService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package mate.academy.service;

import java.util.List;
import java.util.Optional;
import mate.academy.model.Book;

public interface BookService {
Book createBook(Book book);

Optional<Book> findBookById(Long id);

List<Book> findAllBooks();

Book updateBook(Book book);

boolean deleteBookById(Long id);

boolean deleteAll();
}
44 changes: 44 additions & 0 deletions src/main/java/mate/academy/service/BookServiceImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package mate.academy.service;

import java.util.List;
import java.util.Optional;
import mate.academy.dao.BookDao;
import mate.academy.model.Book;

public class BookServiceImpl implements BookService {
private final BookDao bookDao;

public BookServiceImpl(BookDao bookDao) {
this.bookDao = bookDao;
}

@Override
public Book createBook(Book book) {
return bookDao.create(book);
}

@Override
public Optional<Book> findBookById(Long id) {
return bookDao.findById(id);
}

@Override
public List<Book> findAllBooks() {
return bookDao.findAll();
}

@Override
public Book updateBook(Book book) {
return bookDao.update(book);
}

@Override
public boolean deleteBookById(Long id) {
return bookDao.deleteById(id);
}

@Override
public boolean deleteAll() {
return bookDao.deleteAll();
}
}
Loading
Loading