-
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
Mydb #358
Open
MarynaBodina
wants to merge
7
commits into
mate-academy:main
Choose a base branch
from
MarynaBodina:mydb
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
Mydb #358
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
db83d97
'database is done'
MarynaBodina d7a5051
'database is done'
MarynaBodina d69c9ab
'database is done'
MarynaBodina 9f1fec9
'database is done'
MarynaBodina d2dd729
'database is done'
MarynaBodina 7a90f6e
'database is done'
MarynaBodina e9b50b6
'database is done'
MarynaBodina 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,41 @@ | ||
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); | ||
|
||
List<Book> books = List.of( | ||
new Book("OnePiece", new BigDecimal(195)), | ||
new Book("Naruto", new BigDecimal(235)), | ||
new Book("Jujutsu Kaisen", new BigDecimal(243)) | ||
); | ||
|
||
books.forEach(bookDao::create); | ||
|
||
Book book1Update = new Book(1L, "OnePiece", new BigDecimal(250)); | ||
Book updatedBook = bookDao.update(book1Update); | ||
System.out.println("Updated book: " + updatedBook); | ||
|
||
List<Book> allBooks = bookDao.findAll(); | ||
System.out.println("All books:"); | ||
allBooks.forEach(System.out::println); | ||
|
||
Optional<Book> bookById = bookDao.findById(1L); | ||
System.out.println("Book found by id: " + bookById.orElse(null)); | ||
|
||
bookDao.deleteById(3L); | ||
|
||
List<Book> listAfterDelete = bookDao.findAll(); | ||
System.out.println("List after delete by id:"); | ||
listAfterDelete.forEach(System.out::println); | ||
} | ||
} |
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.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); | ||
} |
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,164 @@ | ||
package mate.academy.dao; | ||
|
||
import java.sql.Connection; | ||
import java.sql.PreparedStatement; | ||
import java.sql.ResultSet; | ||
import java.sql.SQLException; | ||
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; | ||
import mate.academy.util.ConnectionUtil; | ||
|
||
@Dao | ||
public class BookDaoImpl implements BookDao { | ||
@Override | ||
public Book create(Book book) { | ||
String query = "INSERT INTO books (title, price) VALUES (?, ?)"; | ||
Connection connection = null; | ||
PreparedStatement preparedStatement = null; | ||
ResultSet generatedKeys = null; | ||
try { | ||
connection = ConnectionUtil.getConnection(); | ||
preparedStatement = connection.prepareStatement( | ||
query, PreparedStatement.RETURN_GENERATED_KEYS); | ||
preparedStatement.setString(1, book.getTitle()); | ||
preparedStatement.setBigDecimal(2, book.getPrice()); | ||
int affectedRows = preparedStatement.executeUpdate(); | ||
if (affectedRows == 0) { | ||
throw new DataProcessingException( | ||
"Creating book failed, no rows affected.", new SQLException()); | ||
} | ||
generatedKeys = preparedStatement.getGeneratedKeys(); | ||
if (generatedKeys.next()) { | ||
Long id = generatedKeys.getLong(1); | ||
book.setId(id); | ||
} else { | ||
throw new DataProcessingException( | ||
"Creating book failed, no ID obtained.", new SQLException()); | ||
} | ||
return book; | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Failed to create a book", e); | ||
} finally { | ||
closeResources(connection, preparedStatement, generatedKeys); | ||
} | ||
} | ||
|
||
@Override | ||
public Optional<Book> findById(Long id) { | ||
String query = "SELECT * FROM books WHERE id = ?"; | ||
try (Connection connection = ConnectionUtil.getConnection(); | ||
PreparedStatement preparedStatement = | ||
connection.prepareStatement(query)) { | ||
preparedStatement.setLong(1, id); | ||
try (ResultSet resultSet = preparedStatement.executeQuery()) { | ||
if (resultSet.next()) { | ||
return Optional.of(new Book( | ||
resultSet.getLong("id"), | ||
resultSet.getString("title"), | ||
resultSet.getBigDecimal("price"))); | ||
} | ||
} | ||
return Optional.empty(); | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Failed to find a book by id: " + id, e); | ||
} | ||
} | ||
|
||
@Override | ||
public List<Book> findAll() { | ||
String query = "SELECT * FROM books"; | ||
try (Connection connection = ConnectionUtil.getConnection(); | ||
PreparedStatement preparedStatement = connection.prepareStatement(query); | ||
ResultSet resultSet = preparedStatement.executeQuery()) { | ||
List<Book> books = new ArrayList<>(); | ||
while (resultSet.next()) { | ||
books.add(new Book( | ||
resultSet.getLong("id"), | ||
resultSet.getString("title"), | ||
resultSet.getBigDecimal("price"))); | ||
} | ||
return books; | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Failed to find all books", e); | ||
} | ||
} | ||
|
||
@Override | ||
public Book update(Book book) { | ||
String query = "UPDATE books SET title = ?, price = ? WHERE id = ?"; | ||
Connection connection = null; | ||
PreparedStatement preparedStatement = null; | ||
try { | ||
connection = ConnectionUtil.getConnection(); | ||
preparedStatement = connection.prepareStatement(query); | ||
preparedStatement.setString(1, book.getTitle()); | ||
preparedStatement.setBigDecimal(2, book.getPrice()); | ||
preparedStatement.setLong(3, book.getId()); | ||
int affectedRows = preparedStatement.executeUpdate(); | ||
if (affectedRows == 0) { | ||
throw new DataProcessingException( | ||
"Updating book failed, no rows affected.", new SQLException()); | ||
} | ||
return book; | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Failed to update a book", e); | ||
} finally { | ||
closeResources(connection, preparedStatement); | ||
} | ||
} | ||
|
||
@Override | ||
public boolean deleteById(Long id) { | ||
String query = "DELETE FROM books WHERE id = ?"; | ||
Connection connection = null; | ||
PreparedStatement preparedStatement = null; | ||
try { | ||
connection = ConnectionUtil.getConnection(); | ||
preparedStatement = connection.prepareStatement(query); | ||
preparedStatement.setLong(1, id); | ||
int affectedRows = preparedStatement.executeUpdate(); | ||
if (affectedRows == 0) { | ||
throw new DataProcessingException( | ||
"Deleting book failed, no rows affected.", new SQLException()); | ||
} | ||
return affectedRows > 0; | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Failed to delete a book with id: " + id, e); | ||
} finally { | ||
closeResources(connection, preparedStatement); | ||
} | ||
} | ||
|
||
private void closeResources(Connection connection, PreparedStatement preparedStatement) { | ||
closeResources(connection, preparedStatement, null); | ||
} | ||
|
||
private void closeResources(Connection connection, | ||
PreparedStatement preparedStatement, ResultSet resultSet) { | ||
if (resultSet != null) { | ||
try { | ||
resultSet.close(); | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Failed to close ResultSet", e); | ||
} | ||
} | ||
if (preparedStatement != null) { | ||
try { | ||
preparedStatement.close(); | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Failed to close PreparedStatement", e); | ||
} | ||
} | ||
if (connection != null) { | ||
try { | ||
connection.close(); | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Failed to close Connection", e); | ||
} | ||
} | ||
} | ||
} |
7 changes: 7 additions & 0 deletions
7
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,7 @@ | ||
package mate.academy.exception; | ||
|
||
public class DataProcessingException extends RuntimeException { | ||
public DataProcessingException(String message, Throwable ex) { | ||
super(message, ex); | ||
} | ||
} |
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,53 @@ | ||
package mate.academy.model; | ||
|
||
import java.math.BigDecimal; | ||
|
||
public class Book { | ||
private Long id; | ||
private String title; | ||
private BigDecimal price; | ||
|
||
public Book(String title, BigDecimal price) { | ||
this.title = title; | ||
this.price = price; | ||
} | ||
|
||
public Book(Long id, String title, BigDecimal price) { | ||
this.id = id; | ||
this.title = title; | ||
this.price = 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,36 @@ | ||
package mate.academy.util; | ||
|
||
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/mydatabase?serverTimezone=UTC"; | ||
private static final Properties DB_PROPERTIES; | ||
private static Connection connection; | ||
|
||
static { | ||
DB_PROPERTIES = new Properties(); | ||
DB_PROPERTIES.put("user", "mary"); | ||
DB_PROPERTIES.put("password", "1905Z"); | ||
|
||
try { | ||
Class.forName("com.mysql.cj.jdbc.Driver"); | ||
} catch (ClassNotFoundException e) { | ||
throw new RuntimeException("Can not load JDBC driver", e); | ||
} | ||
} | ||
|
||
private ConnectionUtil() { | ||
|
||
} | ||
|
||
public static Connection getConnection() throws SQLException { | ||
if (connection == null || connection.isClosed()) { | ||
connection = DriverManager.getConnection(DB_URL, DB_PROPERTIES); | ||
} | ||
return connection; | ||
} | ||
} |
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,6 @@ | ||
CREATE TABLE IF NOT EXISTS books ( | ||
id BIGINT NOT NULL AUTO_INCREMENT, | ||
title VARCHAR(255), | ||
price INT, | ||
PRIMARY KEY(id) | ||
); |
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.
Let's create list of books here