-
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
Solved task jv-jdbc-intro: #351
base: main
Are you sure you want to change the base?
Changes from 1 commit
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,31 @@ | ||
package mate.academy; | ||
|
||
import java.math.BigDecimal; | ||
import java.util.List; | ||
import mate.academy.dao.BookDao; | ||
import mate.academy.entity.Book; | ||
import mate.academy.lib.Injector; | ||
|
||
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("Heroes Land", new BigDecimal(15)); | ||
Book savedBook = bookDao.create(book); | ||
System.out.println(savedBook); | ||
|
||
List<Book> bookList = bookDao.findAll(); | ||
bookList.forEach(System.out::println); | ||
|
||
Book bookFromDB = bookDao.findById(1L).get(); | ||
System.out.println(bookFromDB); | ||
|
||
bookFromDB.setPrice(new BigDecimal(25)); | ||
Book updatedBook = bookDao.update(bookFromDB); | ||
System.out.println(updatedBook); | ||
|
||
boolean isDeleted = bookDao.deleteById(1L); | ||
System.out.println(isDeleted); | ||
} | ||
} |
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.entity.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,105 @@ | ||
package mate.academy.dao.impl; | ||
|
||
import static mate.academy.util.Constants.GET_ALL_BOOKS_QUERY; | ||
import static mate.academy.util.Constants.GET_BOOK_BY_ID_QUERY; | ||
import static mate.academy.util.Constants.SAVE_BOOK_QUERY; | ||
import static mate.academy.util.Constants.UPDATE_BOOK_QUERY; | ||
|
||
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.entity.Book; | ||
import mate.academy.exception.DataProcessingException; | ||
import mate.academy.lib.Dao; | ||
import mate.academy.util.ConnectionUtil; | ||
|
||
@Dao | ||
public class BookDaoImpl implements BookDao { | ||
|
||
@Override | ||
public Book create(Book book) { | ||
try (PreparedStatement createBookStatement = ConnectionUtil.getConnection() | ||
.prepareStatement(SAVE_BOOK_QUERY, Statement.RETURN_GENERATED_KEYS)) { | ||
createBookStatement.setString(1, book.getTitle()); | ||
createBookStatement.setBigDecimal(2, book.getPrice()); | ||
createBookStatement.executeUpdate(); | ||
ResultSet generatedKeys = createBookStatement.getGeneratedKeys(); | ||
if (generatedKeys.next()) { | ||
book.setId(generatedKeys.getObject(1, Long.class)); | ||
} | ||
return book; | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Can`t add book " + book + " to DB", e); | ||
} | ||
} | ||
|
||
@Override | ||
public Optional<Book> findById(Long id) { | ||
try (PreparedStatement getBookByIdStatement = | ||
ConnectionUtil.getConnection().prepareStatement(GET_BOOK_BY_ID_QUERY)) { | ||
getBookByIdStatement.setLong(1, id); | ||
ResultSet resultSet = getBookByIdStatement.executeQuery(); | ||
Book book = null; | ||
if (resultSet.next()) { | ||
book = parseBookFromResultSet(resultSet); | ||
} | ||
return Optional.ofNullable(book); | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Can't get book by id: " + id + " from DB", e); | ||
} | ||
} | ||
|
||
@Override | ||
public List<Book> findAll() { | ||
List<Book> books = new ArrayList<>(); | ||
try (PreparedStatement getAllBooksStatement = | ||
ConnectionUtil.getConnection().prepareStatement(GET_ALL_BOOKS_QUERY)) { | ||
ResultSet resultSet = getAllBooksStatement.executeQuery(); | ||
while (resultSet.next()) { | ||
books.add(parseBookFromResultSet(resultSet)); | ||
} | ||
return books; | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Can't get books from DB", e); | ||
} | ||
} | ||
|
||
@Override | ||
public Book update(Book book) { | ||
try (PreparedStatement upadateBookStatment = | ||
ConnectionUtil.getConnection().prepareStatement( | ||
UPDATE_BOOK_QUERY, Statement.RETURN_GENERATED_KEYS)) { | ||
upadateBookStatment.setString(1, book.getTitle()); | ||
upadateBookStatment.setBigDecimal(2, book.getPrice()); | ||
upadateBookStatment.setLong(3, book.getId()); | ||
upadateBookStatment.executeUpdate(); | ||
return book; | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Can't update book: " + book + " in DB", e); | ||
} | ||
} | ||
|
||
@Override | ||
public boolean deleteById(Long id) { | ||
try (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement( | ||
"DELETE FROM books WHERE id=?", Statement.RETURN_GENERATED_KEYS)) { | ||
statement.setLong(1, id); | ||
return statement.executeUpdate() > 0; | ||
} catch (SQLException e) { | ||
throw new DataProcessingException("Can't delete book by id: " + id + " from DB", e); | ||
} | ||
} | ||
|
||
private Book parseBookFromResultSet(ResultSet resultSet) throws SQLException { | ||
return new Book( | ||
resultSet.getLong("id"), | ||
resultSet.getString("title"), | ||
resultSet.getBigDecimal("price") | ||
); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package mate.academy.entity; | ||
|
||
import java.math.BigDecimal; | ||
|
||
public class Book { | ||
private long id; | ||
private String title; | ||
private BigDecimal price; | ||
|
||
public Book(long id, String title, BigDecimal price) { | ||
this.id = id; | ||
this.title = title; | ||
this.price = price; | ||
} | ||
|
||
public Book(String title, BigDecimal price) { | ||
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 String.format("Book: {id: %d title - %s, price - %s}", id, title, price); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change | ||
---|---|---|---|---|
@@ -0,0 +1,8 @@ | ||||
package mate.academy.exception; | ||||
|
||||
public class DataProcessingException extends RuntimeException { | ||||
|
||||
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.
Suggested change
|
||||
public DataProcessingException(String message, Throwable cause) { | ||||
super(message, cause); | ||||
} | ||||
} |
Original file line number | Diff line number | Diff line change | ||
---|---|---|---|---|
@@ -0,0 +1,8 @@ | ||||
package mate.academy.exception; | ||||
|
||||
public class DbException extends RuntimeException { | ||||
|
||||
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.
Suggested change
|
||||
public DbException(String message) { | ||||
super(message); | ||||
} | ||||
} |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,33 @@ | ||||||
package mate.academy.util; | ||||||
|
||||||
import java.io.FileInputStream; | ||||||
import java.io.IOException; | ||||||
import java.sql.Connection; | ||||||
import java.sql.DriverManager; | ||||||
import java.sql.SQLException; | ||||||
import java.util.Properties; | ||||||
import mate.academy.exception.DbException; | ||||||
|
||||||
public class ConnectionUtil { | ||||||
private static final Properties dbProperties = new Properties(); | ||||||
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.
Suggested change
constant naming convention |
||||||
|
||||||
static { | ||||||
try { | ||||||
dbProperties.load(new FileInputStream(Constants.APP_PROPERTIES_FILE)); | ||||||
Class.forName(dbProperties.getProperty(Constants.DB_DRIVER_TAG)); | ||||||
} catch (IOException e) { | ||||||
throw new DbException("Can`t load JDBC driver for MYSQL: " + e.getMessage()); | ||||||
} catch (ClassNotFoundException e) { | ||||||
throw new DbException("Can`t load driver properties: " + e.getMessage()); | ||||||
} | ||||||
} | ||||||
|
||||||
public static Connection getConnection() { | ||||||
try { | ||||||
return DriverManager.getConnection( | ||||||
dbProperties.getProperty(Constants.DB_URL_TAG)); | ||||||
} catch (SQLException e) { | ||||||
throw new DbException("Can`t create connection for DB: " + e.getMessage()); | ||||||
} | ||||||
} | ||||||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package mate.academy.util; | ||
|
||
public class Constants { | ||
// Application paths | ||
public static final String APP_PROPERTIES_FILE = "src/main/resources/app.properties"; | ||
// DB connection constants | ||
public static final String DB_DRIVER_TAG = "db.driver"; | ||
public static final String DB_URL_TAG = "db.connection.url"; | ||
// Book dao sql query | ||
public static final String SAVE_BOOK_QUERY = "INSERT INTO books(title, price) VALUES(?, ?)"; | ||
public static final String GET_BOOK_BY_ID_QUERY = "SELECT * FROM books WHERE id = ?"; | ||
public static final String GET_ALL_BOOKS_QUERY = "SELECT * FROM books"; | ||
public static final String UPDATE_BOOK_QUERY = | ||
"UPDATE books SET title = ?, price = ? WHERE id = ?"; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
db.driver=com.mysql.cj.jdbc.Driver | ||
db.connection.url=jdbc:mysql://localhost:3306/testdb?user=root&password=root |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
CREATE SCHEMA IF NOT EXISTS testdb DEFAULT CHARACTER SET utf8; | ||
USE testdb; | ||
|
||
CREATE TABLE IF NOT EXISTS books ( | ||
id bigint AUTO_INCREMENT PRIMARY KEY, | ||
title varchar(45) NOT NULL, | ||
price decimal DEFAULT 0, | ||
); |
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.
Do you need to check affected rows?
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.
I don't think so.