Skip to content

Commit

Permalink
do HW
Browse files Browse the repository at this point in the history
  • Loading branch information
RetKinf committed Apr 28, 2024
1 parent bc1d800 commit c5fb0f6
Show file tree
Hide file tree
Showing 8 changed files with 284 additions and 1 deletion.
8 changes: 8 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@
</maven.checkstyle.plugin.configLocation>
</properties>

<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
Expand Down
32 changes: 32 additions & 0 deletions src/main/java/mate/academy/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package mate.academy;

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/hw";
private static final Properties DB_PROPERTIES;

static {
DB_PROPERTIES = new Properties();
DB_PROPERTIES.put("user", "root");
DB_PROPERTIES.put("password", "new_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() {
try {
return DriverManager
.getConnection(DB_URL, DB_PROPERTIES);
} catch (SQLException e) {
throw new RuntimeException("Can not create a connection with DB", e);
}
}
}
7 changes: 7 additions & 0 deletions src/main/java/mate/academy/DataProcessingException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package mate.academy;

public class DataProcessingException extends RuntimeException {
public DataProcessingException(String errorMessage, Throwable ex) {
super(errorMessage, ex);
}
}
13 changes: 12 additions & 1 deletion src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
package mate.academy;

import java.math.BigDecimal;
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);
Book book1 = new Book(7L,"Mermaid", new BigDecimal(100));
book1.setPrice(BigDecimal.valueOf(150));
bookDao.update(book1);
System.out.println(bookDao.findAll());
}
}
17 changes: 17 additions & 0 deletions src/main/java/mate/academy/dao/BookDao.java
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);
}
150 changes: 150 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
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.ConnectionUtil;
import mate.academy.DataProcessingException;
import mate.academy.lib.Dao;
import mate.academy.model.Book;

@Dao
public class BookDaoImpl implements BookDao {
private static Connection connection;
private static final String INSERT_QUERY = "INSERT INTO books (title, price) VALUES (?, ?)";
private static final String SELECT_BY_ID_QUERY = "SELECT * FROM books WHERE id = ?";
private static final String SELECT_ALL_QUERY = "SELECT * FROM books";
private static final String UPDATE_QUERY = "UPDATE books SET title = ?, price = ? WHERE id = ?";
private static final String DELETE_QUERY = "DELETE FROM books WHERE id = ?";

public BookDaoImpl() {
connection = ConnectionUtil.getConnection();
}

@Override
public Book create(Book book) {
checkBook(book);
if (book.getId() != null) {
throw new RuntimeException("Book id must be null");
}
try (PreparedStatement statement = connection.prepareStatement(
INSERT_QUERY, Statement.RETURN_GENERATED_KEYS
)) {
statementSet(statement, book);
int affectedRows = statement.executeUpdate();
if (affectedRows < 1) {
throw new RuntimeException(
"Expected to insert at least one row, but inserted 0 rows."
);
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
book.setId(generatedKeys.getLong(1));
}
}
} catch (SQLException e) {
throw new DataProcessingException("Can't add new book", e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
checkId(id);
try (PreparedStatement statement = connection.prepareStatement(SELECT_BY_ID_QUERY)) {
statement.setLong(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(resultBook(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't find book with id:" + id, e);
}
return Optional.empty();
}

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
try (PreparedStatement statement = connection.prepareStatement(SELECT_ALL_QUERY)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
books.add(resultBook(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't find books", e);
}
return books;
}

@Override
public Book update(Book book) {
checkBook(book);
checkId(book.getId());
try (PreparedStatement statement = connection.prepareStatement(UPDATE_QUERY)) {
statementSet(statement, book);
statement.setLong(3, book.getId());
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new RuntimeException("Book with id " + book.getId() + " not found.");
}
} catch (SQLException e) {
throw new DataProcessingException("Can't update book " + book, e);
}
return book;
}

@Override
public boolean deleteById(Long id) {
checkId(id);
try (PreparedStatement statement = connection.prepareStatement(DELETE_QUERY)) {
statement.setLong(1, id);
int affectedRows = statement.executeUpdate();
return affectedRows > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can't delete book with id: " + id, e);
}
}

private void checkId(Long id) {
if (id <= 0) {
throw new RuntimeException("ID can't be zero or negative");
}
}

private void checkBook(Book book) {
if (book == null) {
throw new IllegalArgumentException("Book cannot be null");
}
if (book.getTitle() == null) {
throw new IllegalArgumentException("Title is null");
}
}

private Book resultBook(ResultSet resultSet) {
try {
return new Book(
resultSet.getObject("id", Long.class),
resultSet.getString("title"),
resultSet.getObject("price", BigDecimal.class)
);
} catch (SQLException e) {
throw new DataProcessingException("Can't get the book", e);
}
}

private void statementSet(PreparedStatement statement, Book book) {
try {
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
} catch (SQLException e) {
throw new DataProcessingException("Can't to set statement", e);
}
}
}
53 changes: 53 additions & 0 deletions src/main/java/mate/academy/model/Book.java
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(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 "Book{"
+ "id=" + id
+ ", title='" + title + '\''
+ ", price=" + price
+ '}';
}
}
5 changes: 5 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS books(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NULL
)

0 comments on commit c5fb0f6

Please sign in to comment.