-
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
jdbc-solution - V1.0 #313
base: main
Are you sure you want to change the base?
jdbc-solution - V1.0 #313
Changes from 3 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,34 @@ | ||
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 { | ||
private static final Injector injector = Injector.getInstance("mate.academy"); | ||
|
||
public static void main(String[] args) { | ||
BookDao bookDao = (BookDao) injector.getInstance(BookDao.class); | ||
Book book = new Book(); | ||
book.setTitle("Dune"); | ||
book.setPrice(BigDecimal.valueOf(19.99)); | ||
bookDao.create(book); | ||
|
||
// Testing other methods | ||
Optional<Book> foundBook = bookDao.findById(book.getId()); | ||
foundBook.ifPresent(System.out::println); | ||
|
||
List<Book> allBooks = bookDao.findAll(); | ||
System.out.println("All Books: " + allBooks); | ||
|
||
book.setTitle("Lisan al gaib"); | ||
bookDao.update(book); | ||
System.out.println("Updated Book: " + book); | ||
|
||
boolean deleted = bookDao.deleteById(book.getId()); | ||
System.out.println("Deleted: " + deleted); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package mate.academy.connection; | ||
|
||
import java.sql.Connection; | ||
import java.sql.DriverManager; | ||
import java.sql.SQLException; | ||
import java.util.Properties; | ||
import mate.academy.exception.DataProcessingException; | ||
|
||
public class ConnectionUtil { | ||
private static final String DRIVER = "com.mysql.cj.jdbc.Driver"; | ||
private static final String DB_PATH = "jdbc:mysql://localhost:3306/jdbc"; | ||
private static final String USER = "root"; | ||
private static final String PASSWORD = "MySQL1234"; | ||
private static final Properties PROPERTIES; | ||
|
||
static { | ||
PROPERTIES = new Properties(); | ||
PROPERTIES.put("user", USER); | ||
PROPERTIES.put("password", PASSWORD); | ||
|
||
try { | ||
Class.forName(DRIVER); | ||
} catch (ClassNotFoundException e) { | ||
throw new DataProcessingException("Something wrong with Driver", e); | ||
} | ||
} | ||
|
||
public static Connection getConnection() { | ||
try { | ||
return DriverManager.getConnection(DB_PATH, PROPERTIES); | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Failed to establish database connection", e); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
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); | ||
} |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,126 @@ | ||||||
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.connection.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 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 to insert at least one row, but inserted 0 rows for book: " | ||||||
+ book); | ||||||
} | ||||||
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. code duplication in the update method, extract it to a method |
||||||
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 save new book: " + book, e); | ||||||
} | ||||||
return book; | ||||||
} | ||||||
|
||||||
@Override | ||||||
public Optional<Book> findById(Long id) { | ||||||
Book book = null; | ||||||
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()) { | ||||||
book = mapResultToBook(resultSet); | ||||||
} | ||||||
} catch (SQLException e) { | ||||||
throw new DataProcessingException("Can't get a book by id " + id, e); | ||||||
} | ||||||
return Optional.ofNullable(book); | ||||||
} | ||||||
|
||||||
@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()) { | ||||||
Book book = mapResultToBook(resultSet); | ||||||
books.add(book); | ||||||
} | ||||||
} catch (SQLException e) { | ||||||
throw new DataProcessingException("Can't fetch 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()); | ||||||
|
||||||
int affectedRows = statement.executeUpdate(); | ||||||
if (affectedRows < 1) { | ||||||
throw new DataProcessingException( | ||||||
"Expected to update at least one row, but updated 0 rows for book: " | ||||||
+ book); | ||||||
} | ||||||
} catch (SQLException e) { | ||||||
throw new DataProcessingException("Can't update a book: " + book, e); | ||||||
} | ||||||
return book; | ||||||
} | ||||||
|
||||||
@Override | ||||||
public boolean deleteById(Long id) { | ||||||
String sql = "DELETE FROM books WHERE id = ?"; | ||||||
int affectedRows; | ||||||
try (Connection connection = ConnectionUtil.getConnection(); | ||||||
PreparedStatement statement = connection.prepareStatement(sql)) { | ||||||
statement.setLong(1, id); | ||||||
affectedRows = statement.executeUpdate(); | ||||||
} catch (SQLException e) { | ||||||
throw new DataProcessingException("Can't delete a book with id: " + id, e); | ||||||
} | ||||||
return affectedRows > 0; | ||||||
} | ||||||
|
||||||
private Book mapResultToBook(ResultSet resultSet) throws SQLException { | ||||||
Long id = resultSet.getLong("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. as it was mentioned in the common mistakes
Suggested change
|
||||||
String title = resultSet.getString("title"); | ||||||
BigDecimal price = resultSet.getObject("price", BigDecimal.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. let's make those strings constant |
||||||
|
||||||
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,11 @@ | ||
package mate.academy.exception; | ||
|
||
public class DataProcessingException extends RuntimeException { | ||
public DataProcessingException(String message, Throwable ex) { | ||
super(message, ex); | ||
} | ||
|
||
public DataProcessingException(String message) { | ||
super(message); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
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 + '}'; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,6 @@ | ||||||
USE jdbc; | ||||||
CREATE TABLE books ( | ||||||
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, | ||||||
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. Primary key already contains not null constraint in it
Suggested change
|
||||||
title VARCHAR(255), | ||||||
price DECIMAL | ||||||
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. I'd rather specify the ranges
Suggested change
|
||||||
); |
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.
magic numbers, check other methods as well