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

jv-jdbc-intro #422

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 @@ -17,7 +17,14 @@
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>
<plugin>
Expand Down Expand Up @@ -54,5 +61,6 @@
</plugin>
</plugins>
</pluginManagement>

</build>
</project>
42 changes: 40 additions & 2 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,45 @@
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 {
public static void main(String[] args) {
private static final Injector INJECTOR = Injector.getInstance("mate.academy");

public static void main(String[] args) {
BookDao bookDao = (BookDao) INJECTOR.getInstance(BookDao.class);
Optional<Book> foundBook = bookDao.findById(1L);
if (foundBook.isPresent()) {
System.out.println("Book found: " + foundBook.get());
Book bookToUpdate = foundBook.get();
bookToUpdate.setTitle("Alice in Wonderland");
bookToUpdate.setPrice(new BigDecimal("120.00"));
bookDao.update(bookToUpdate);
System.out.println("Book updated: " + bookToUpdate);
} else {
System.out.println("Book not found. Creating a new book.");
Book book = new Book();
book.setPrice(new BigDecimal("100.00"));
book.setTitle("Alice");
bookDao.create(book);
System.out.println("Book created: " + book);
}

List<Book> allBooks = bookDao.findAll();
System.out.println("All books in the database:");
for (Book b : allBooks) {
System.out.println(b);
}

boolean isDeleted = bookDao.deleteById(1L);
if (isDeleted) {
System.out.println("Book with ID 1 deleted.");
} else {
System.out.println("Book with ID 1 not found.");
}
}
}
}
20 changes: 20 additions & 0 deletions src/main/java/mate/academy/dao/BookDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package mate.academy.dao;

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

@Dao
public interface BookDao {

Book create(Book book);

Optional<Book> findById(Long id);

List<Book> findAll();

Book update(Book book);

boolean deleteById(Long id);

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package mate.academy.lib;
package mate.academy.dao;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
Expand Down
128 changes: 128 additions & 0 deletions src/main/java/mate/academy/dao/impl/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package mate.academy.dao.impl;

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.dao.BookDao;
import mate.academy.dao.Dao;
import mate.academy.exceptions.DataProcessingException;
import mate.academy.lib.ConnectionUtil;
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 (?, ?)";

Choose a reason for hiding this comment

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

Remember about SQL style: use uppercase for SQL keywords in your queries.

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

Choose a reason for hiding this comment

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

Use Statement.RETURN_GENERATED_KEYS only in create statement, it's not needed in other methods.

Choose a reason for hiding this comment

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

Use PreparedStatement over Statement, even for a static query with no parameters in findAll() method. It's the best practice, and it's slightly faster.

statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
if (statement.executeUpdate() < 1) {
throw new RuntimeException("Expected to insert 1 record but inserted 0 rows");
}
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 book: " + book, e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
String sql = "SELECT * FROM books WHERE id = ?";
if (id == null) {
return Optional.empty();
}
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String title = resultSet.getObject("title", String.class);

Choose a reason for hiding this comment

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

Be attentive with retrieving the data from ResultSet: use resultSet.getObject("title", String.class) instead of resultSet.getString("title") to handle possible null values correctly.

BigDecimal price = resultSet.getObject("price", BigDecimal.class);

Book book = new Book();
book.setId(id);
book.setPrice(price);
book.setTitle(title);
Comment on lines +53 to +60

Choose a reason for hiding this comment

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

Try to avoid code duplication. Especially, when you are working with ResultSet. Move retrieving data from ResultSet into Entity object to a separate private method.

Comment on lines +57 to +60

Choose a reason for hiding this comment

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

When you convert ResultSet to Book, better create an object using setters or constructor but not both of them, because it's not consistent to use both ways of initialization of an object.

return Optional.of(book);
}
return Optional.empty();
} catch (SQLException e) {
throw new DataProcessingException("Can't get 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.

Use informative messages for exceptions. Include the id that caused the exception in the message.

}
}

@Override
public List<Book> findAll() {
String sql = "SELECT * FROM books";
List<Book> books = new ArrayList<>();
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Long id = resultSet.getObject("id", Long.class);
String title = resultSet.getObject("title", String.class);
BigDecimal price = resultSet.getObject("price", BigDecimal.class);

Book book = new Book();
book.setId(id);
book.setPrice(price);
book.setTitle(title);
books.add(book);
Comment on lines +74 to +85

Choose a reason for hiding this comment

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

Use PreparedStatement over Statement for the findAll() method as well. And consider moving the ResultSet processing into a separate private method to avoid duplication.

}
} 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 = ?";

Choose a reason for hiding this comment

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

Remember about SQL style: use uppercase for SQL keywords in your queries.

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

Choose a reason for hiding this comment

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

There's no need to use Statement.RETURN_GENERATED_KEYS in the update method.

statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
statement.setLong(3, book.getId());
if (statement.executeUpdate() < 1) {
throw new RuntimeException("Expected to insert 1 record but inserted 0 rows");
Comment on lines +102 to +103

Choose a reason for hiding this comment

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

The exception message is misleading. This is an update operation, not an insert. Consider changing the message to reflect that no rows were updated.

}
return book;
} catch (SQLException e) {
throw new DataProcessingException("Can't update book " + book, e);
}
}

@Override
public boolean deleteById(Long id) {
if (id == null) {
return false;
}
String sql = "DELETE FROM books WHERE id = ?";

Choose a reason for hiding this comment

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

Remember about SQL style: use uppercase for SQL keywords in your queries.

try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, id);
if (statement.executeUpdate() < 1) {
return false;
Comment on lines +120 to +121

Choose a reason for hiding this comment

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

Don't return true all the time in the method delete. Let's return boolean value depending on preparedStatement.executeUpdate() result.

}
} catch (SQLException e) {
throw new DataProcessingException("Can't delete 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.

Use informative messages for exceptions. Include the id that caused the exception in the message.

}
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package mate.academy.exceptions;

public class DataProcessingException extends RuntimeException {
public DataProcessingException(String message, Throwable ex) {
super(message, ex);
}
}
29 changes: 29 additions & 0 deletions src/main/java/mate/academy/lib/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
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/test";

Choose a reason for hiding this comment

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

The DB_URL is incomplete, it should contain the full JDBC URL to connect to the database. Make sure to specify the database name, and any other necessary configurations.

private static final String USER = "root";
private static final String PASSWORD = "qwerty123";
Comment on lines +10 to +12

Choose a reason for hiding this comment

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

Storing database credentials directly in the code is a bad practice due to security reasons. It's better to use environment variables or configuration files that are not included in the version control.

private static final Properties DB_PROPERTIES;

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

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL);

Choose a reason for hiding this comment

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

You should pass the DB_PROPERTIES to the getConnection method to ensure the user and password are included in the connection.

}
Comment on lines +26 to +28

Choose a reason for hiding this comment

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

According to the checklist, you should not use the schema's name in your queries. However, it's not clear if the DB_URL includes the schema name or not due to the incomplete URL. Make sure the schema name is not included in the DB_URL.

}
1 change: 1 addition & 0 deletions src/main/java/mate/academy/lib/Injector.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mate.academy.dao.Dao;

public class Injector {
private static final Map<String, Injector> injectors = new HashMap<>();
Expand Down
62 changes: 62 additions & 0 deletions src/main/java/mate/academy/model/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package mate.academy.model;

import java.math.BigDecimal;
import java.util.Objects;

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 boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Book book = (Book) o;
return Objects.equals(id, book.id)
&& Objects.equals(title, book.title)
&& Objects.equals(price, book.price);
}

@Override
public int hashCode() {
return Objects.hash(id, title, 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 INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
price DECIMAL (10, 2) NOT NULL
}
Loading