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

result #401

Open
wants to merge 3 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
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>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.0.0</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
Expand Down
25 changes: 24 additions & 1 deletion 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 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 final Injector injector = Injector.getInstance("mate.academy.dao");

public static void main(String[] args) {
Book book1 = new Book();
book1.setTitle("book1");
book1.setPrice(BigDecimal.valueOf(200));
Book book2 = new Book();
book2.setTitle("book2");
book2.setPrice(BigDecimal.valueOf(300));
Book updateBook = new Book();
updateBook.setId(1L);
updateBook.setTitle("updatedBook");
updateBook.setPrice(BigDecimal.valueOf(999));
BookDao bookDao = (BookDao) injector.getInstance(BookDao.class);
bookDao.create(book1);
bookDao.create(book2);
System.out.println(bookDao.findById(2L));
System.out.println(bookDao.findAll().toString());
System.out.println(bookDao.deleteById(2L));
bookDao.update(updateBook);
}
}
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);
}
118 changes: 118 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
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.lib.ConnectionUtil;
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 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 RuntimeException("No affected rows");
}

Choose a reason for hiding this comment

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

I think these lines are redundant as you check generatedKeys next

ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
Long id = generatedKeys.getLong(1);
book.setId(id);
}
} catch (SQLException e) {
throw new DataProcessingException("Can't create a book: " + book, e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
String sql = "SELECT * FROM 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(createNewBook(
id,
resultSet.getString("title"),
resultSet.getBigDecimal("price")
));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't get a book by id " + id, e);
}
return Optional.empty();
}

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
String sql = "SELECT * FROM books";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
books.add(createNewBook(
resultSet.getLong("id"),
resultSet.getString("title"),
resultSet.getBigDecimal("price")
));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't find all books", e);
}
return books;
}

@Override
public Book update(Book book) {
String sql = "UPDATE 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());
if (statement.executeUpdate() < 1) {
throw new DataProcessingException("Can't update the book: " + book);
}
} catch (SQLException e) {
throw new DataProcessingException("Can't update the book: " + book, e);
}
return book;
}

@Override
public boolean deleteById(Long id) {
String sql = "DELETE FROM books WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, id);
int affectedRows = statement.executeUpdate();
return affectedRows > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can't delete a book with id: " + id, e);
}
}

private Book createNewBook(Long id, String title, BigDecimal price) {
Book book = new Book();
book.setId(id);
book.setTitle(title);
book.setPrice(price);
return book;
}
}
11 changes: 11 additions & 0 deletions src/main/java/mate/academy/dao/DataProcessingException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.dao;

public class DataProcessingException extends RuntimeException {
public DataProcessingException(String message) {
super(message);
}

public DataProcessingException(String message, Throwable ex) {
super(message, ex);
}
}
27 changes: 27 additions & 0 deletions src/main/java/mate/academy/lib/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package mate.academy.lib;

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/mate_academy";
private static final Properties DB_PROPERTIES;

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

Choose a reason for hiding this comment

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

Hardcoding passwords in the source code is a security risk. Consider using environment variables or a configuration file to store sensitive information securely.


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

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL, DB_PROPERTIES);
}
Comment on lines +24 to +26

Choose a reason for hiding this comment

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

Don't forget to close the Connection object after usage to prevent resource leaks. This can be done using try-with-resources or by calling close() in a finally block.

}
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
+ '}';
}
}
5 changes: 5 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CREATE TABLE books (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL
);
Loading