-
Notifications
You must be signed in to change notification settings - Fork 438
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
base: main
Are you sure you want to change the base?
jv-jdbc-intro #422
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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."); | ||
} | ||
} | ||
} | ||
} |
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 |
---|---|---|
@@ -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 (?, ?)"; | ||
try (Connection connection = ConnectionUtil.getConnection(); | ||
PreparedStatement statement = connection.prepareStatement( | ||
sql, Statement.RETURN_GENERATED_KEYS)) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use |
||
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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Be attentive with retrieving the data from ResultSet: use |
||
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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When you convert |
||
return Optional.of(book); | ||
} | ||
return Optional.empty(); | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Can't get book by id" + id, e); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use |
||
} | ||
} 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 = ?"; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There's no need to use |
||
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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 = ?"; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't return |
||
} | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Can't delete book by id " + id, e); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
} | ||
} |
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"; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
} |
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 | ||
+ '}'; | ||
} | ||
} |
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 | ||
} |
There was a problem hiding this comment.
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.