-
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
Create BookDao interface, MySqlBookDao class #49
Open
Dimagaa
wants to merge
7
commits into
mate-academy:main
Choose a base branch
from
Dimagaa:homework
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
61cf9ac
Create BookDao interface, MySqlBookDao class
Dimagaa 1291b49
Fix codestyle mistakes
Dimagaa 781b6ba
Fix codestyle mistakes
Dimagaa 35b2c11
Fix issues
Dimagaa 7af2bc9
Fix issues
Dimagaa 4382906
Merge branch 'main' into homework
Dimagaa cd7d090
Fix issue
Dimagaa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,59 @@ | ||
package mate.academy; | ||
|
||
import java.math.BigDecimal; | ||
import java.util.List; | ||
import mate.academy.lib.Injector; | ||
import mate.academy.model.Book; | ||
import mate.academy.repository.BookDao; | ||
|
||
public class Main { | ||
private static final Injector INJECTOR = Injector.getInstance("mate.academy"); | ||
private static final List<Book> LIBRARY; | ||
|
||
static { | ||
Book book1 = new Book(); | ||
book1.setTitle("\"Flowers for Algernon\" Daniel Keyes"); | ||
book1.setPrice(BigDecimal.valueOf(8)); | ||
|
||
Book book2 = new Book(); | ||
book2.setTitle("\"Shining\" Stephen King"); | ||
book2.setPrice(BigDecimal.valueOf(13)); | ||
|
||
Book book3 = new Book(); | ||
book3.setTitle("\"Fight Club\" Chuck Palahniuk"); | ||
book3.setPrice(BigDecimal.valueOf(20)); | ||
|
||
LIBRARY = List.of(book1, book2, book3); | ||
} | ||
|
||
public static void main(String[] args) { | ||
//Get BookDao instance using Injector | ||
BookDao bookDao = (BookDao) INJECTOR.getInstance(BookDao.class); | ||
|
||
//Create new books in the database | ||
LIBRARY.forEach(bookDao::create); | ||
|
||
//Read all books from the database and compare it with library list | ||
List<Book> booksFromDB = bookDao.findAll(); | ||
System.out.println("Books from database:"); | ||
booksFromDB.forEach(System.out::println); | ||
|
||
//Find by id | ||
Book bookFromLib = LIBRARY.get(0); | ||
Book bookFromDb = bookDao.findById(bookFromLib.getId()).orElseThrow(); | ||
System.out.println("Book from db: " + bookFromDb + System.lineSeparator()); | ||
|
||
//Update | ||
bookFromLib.setTitle("Updated title"); | ||
bookDao.update(bookFromLib); | ||
bookFromDb = bookDao.findById(bookFromLib.getId()).orElseThrow(); | ||
System.out.println("Expect that title is updated: " | ||
+ bookFromDb + System.lineSeparator()); | ||
|
||
//Delete by id | ||
bookDao.deleteById(bookFromLib.getId()); | ||
|
||
//Delete all books in the database | ||
LIBRARY.forEach(book -> bookDao.deleteById(book.getId())); | ||
} | ||
} |
11 changes: 11 additions & 0 deletions
11
src/main/java/mate/academy/exception/DataProcessingException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | ||
super(message); | ||
} | ||
|
||
public DataProcessingException(String message, Throwable cause) { | ||
super(message, cause); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
+ '}'; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package mate.academy.repository; | ||
|
||
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); | ||
} |
119 changes: 119 additions & 0 deletions
119
src/main/java/mate/academy/repository/MySqlBookDao.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
package mate.academy.repository; | ||
|
||
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.exception.DataProcessingException; | ||
import mate.academy.lib.Dao; | ||
import mate.academy.model.Book; | ||
|
||
@Dao | ||
public class MySqlBookDao implements BookDao { | ||
private static final int ID_PARAMETER_INDEX = 1; | ||
private static final int TITLE_PARAMETER_INDEX = 1; | ||
private static final int PRICE_PARAMETER_INDEX = 2; | ||
private static final int UPDATE_ID_PARAMETER_INDEX = 3; | ||
private static final int ZERO_AFFECTED_ROW = 0; | ||
private static final String ID_ROW_LABEL = "id"; | ||
private static final String TITLE_ROW_LABEL = "title"; | ||
private static final String PRICE_ROW_LABEL = "price"; | ||
|
||
@Override | ||
public Book create(Book book) { | ||
String query = "INSERT INTO book(title, price) VALUES(?, ?)"; | ||
try (Connection connection = MySqlConnectionManager.getConnection(); | ||
PreparedStatement statement = connection | ||
.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { | ||
statement.setString(TITLE_PARAMETER_INDEX, book.getTitle()); | ||
statement.setBigDecimal(PRICE_PARAMETER_INDEX, book.getPrice()); | ||
statement.executeUpdate(); | ||
ResultSet generatedKeys = statement.getGeneratedKeys(); | ||
if (generatedKeys.next()) { | ||
book.setId(generatedKeys.getLong(1)); | ||
} | ||
} catch (SQLException e) { | ||
throw new DataProcessingException( | ||
"Cannot create new book, something gone wrong: " + book, e); | ||
} | ||
return book; | ||
} | ||
|
||
@Override | ||
public Optional<Book> findById(Long id) { | ||
String query = "SELECT * FROM book WHERE id = ?"; | ||
try (Connection connection = MySqlConnectionManager.getConnection(); | ||
PreparedStatement statement = connection.prepareStatement(query)) { | ||
statement.setLong(ID_PARAMETER_INDEX, id); | ||
ResultSet resultSet = statement.executeQuery(); | ||
if (resultSet.next()) { | ||
Book book = parseToObject(resultSet); | ||
return Optional.of(book); | ||
} | ||
} catch (SQLException e) { | ||
throw new DataProcessingException( | ||
"Can't get Book from database by id " + id, e); | ||
} | ||
return Optional.empty(); | ||
} | ||
|
||
@Override | ||
public List<Book> findAll() { | ||
String query = "SELECT * FROM book"; | ||
List<Book> resultList = new ArrayList<>(); | ||
try (Connection connection = MySqlConnectionManager.getConnection(); | ||
PreparedStatement statement = connection.prepareStatement(query)) { | ||
ResultSet resultSet = statement.executeQuery(); | ||
while (resultSet.next()) { | ||
Book book = parseToObject(resultSet); | ||
resultList.add(book); | ||
} | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Cannot get books from database", e); | ||
} | ||
return resultList; | ||
} | ||
|
||
@Override | ||
public Book update(Book book) { | ||
String query = "UPDATE book SET title= ?, price= ? WHERE id = ?"; | ||
try (Connection connection = MySqlConnectionManager.getConnection(); | ||
PreparedStatement statement = connection.prepareStatement(query)) { | ||
statement.setString(TITLE_PARAMETER_INDEX, book.getTitle()); | ||
statement.setBigDecimal(PRICE_PARAMETER_INDEX, book.getPrice()); | ||
statement.setLong(UPDATE_ID_PARAMETER_INDEX, book.getId()); | ||
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. Where is |
||
statement.executeUpdate(); | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Book was not updated: " + book, e); | ||
} | ||
return book; | ||
} | ||
|
||
@Override | ||
public boolean deleteById(Long id) { | ||
String query = "DELETE FROM book WHERE id =?"; | ||
try (Connection connection = MySqlConnectionManager.getConnection(); | ||
PreparedStatement statement = connection.prepareStatement(query)) { | ||
statement.setLong(ID_PARAMETER_INDEX, id); | ||
return statement.executeUpdate() > ZERO_AFFECTED_ROW; | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Cannot delete book by id " + id, e); | ||
} | ||
} | ||
|
||
private Book parseToObject(ResultSet resultSet) throws SQLException { | ||
Long id = resultSet.getObject(ID_ROW_LABEL, Long.class); | ||
String title = resultSet.getString(TITLE_ROW_LABEL); | ||
BigDecimal price = resultSet.getBigDecimal(PRICE_ROW_LABEL); | ||
Book book = new Book(); | ||
book.setId(id); | ||
book.setTitle(title); | ||
book.setPrice(price); | ||
return book; | ||
} | ||
} |
27 changes: 27 additions & 0 deletions
27
src/main/java/mate/academy/repository/MySqlConnectionManager.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package mate.academy.repository; | ||
|
||
import java.sql.Connection; | ||
import java.sql.DriverManager; | ||
import java.sql.SQLException; | ||
import java.util.Properties; | ||
|
||
public class MySqlConnectionManager { | ||
private static final String DB_URL = "jdbc:mysql://localhost:3306/library"; | ||
private static final Properties DB_PROPERTIES; | ||
|
||
static { | ||
DB_PROPERTIES = new Properties(); | ||
DB_PROPERTIES.put("user", "test"); | ||
DB_PROPERTIES.put("password", "StrongSecret1234"); | ||
|
||
try { | ||
Class.forName("com.mysql.cj.jdbc.Driver"); | ||
} catch (ClassNotFoundException e) { | ||
throw new RuntimeException("MySQL JDBC driver not found", e); | ||
} | ||
} | ||
|
||
public static Connection getConnection() throws SQLException { | ||
return DriverManager.getConnection(DB_URL, DB_PROPERTIES); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
CREATE SCHEMA library; | ||
USE library; | ||
CREATE TABLE book ( | ||
id BIGINT AUTO_INCREMENT PRIMARY KEY, | ||
title VARCHAR(255) NOT NULL, | ||
price DECIMAL NOT NULL | ||
) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Is it required to delete this?