Skip to content

Commit

Permalink
solution added
Browse files Browse the repository at this point in the history
  • Loading branch information
xotekijke committed Oct 16, 2024
1 parent bc1d800 commit e137a1b
Show file tree
Hide file tree
Showing 9 changed files with 265 additions and 1 deletion.
9 changes: 9 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
</maven.checkstyle.plugin.configLocation>
</properties>

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

</dependencies>

<build>
<plugins>
<plugin>
Expand Down
27 changes: 27 additions & 0 deletions src/main/java/mate/academy/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
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/book";
private static final Properties DB_PROPERTIES;

static {
DB_PROPERTIES = new Properties();
DB_PROPERTIES.put("user", "root");
DB_PROPERTIES.put("password", "Root1234");

try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Can not load JDBC Driver", e);
}
}

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL, DB_PROPERTIES);
}
}
17 changes: 17 additions & 0 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
package mate.academy;

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(1L, "Last Inch", 30);

bookDao.create(book);
bookDao.findAll().forEach(System.out::println);
System.out.println();
System.out.println("Id 1 " + System.lineSeparator() + bookDao.findById(1L));
bookDao.deleteById(2L);
bookDao.findAll().forEach(System.out::println);
System.out.println();
bookDao.update(book);
bookDao.findAll().forEach(System.out::println);
}
}
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);
}
120 changes: 120 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package mate.academy.dao;

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.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 (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, book.getTitle());
statement.setInt(2, book.getPrice());

int affectedRows = statement.executeUpdate();

if (affectedRows < 1) {
throw new DataProcessingException("Creating book failed, no rows affected.");
}

try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
book.setId(generatedKeys.getObject(1, Long.class));
} else {
throw new DataProcessingException("Creating book failed, no ID obtained.");
}
}
} catch (SQLException e) {
throw new DataProcessingException("Can't create book " + book, e);
}

return book;
}

@Override
public Optional<Book> findById(Long id) {
String sql = "SELECT * FROM books WHERE id = ?";

try (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement(sql)) {
statement.setLong(1, id);

try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return Optional.of(getBook(resultSet));
}
}
} catch (SQLException e) {
throw new DataProcessingException("Can't find by id for id = " + id, e);
}

return Optional.empty();
}

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
String sql = "SELECT * FROM books";

try (PreparedStatement statement = ConnectionUtil
.getConnection().prepareStatement(sql);
ResultSet resultSet = statement.executeQuery()) {

while (resultSet.next()) {
books.add(getBook(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't retrieve all books", e);
}

return books;
}

@Override
public Book update(Book book) {
String sql = "UPDATE books SET price = ?, title = ? WHERE id = ?";
try (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement(sql)) {
statement.setInt(1, book.getPrice());
statement.setString(2, book.getTitle());
statement.setLong(3, book.getId());
if (statement.executeUpdate() > 0) {
return book;
} else {
throw new DataProcessingException("No book found with id = " + book.getId(),
new RuntimeException());
}
} catch (SQLException e) {
throw new DataProcessingException("Can't update book with id = " + book.getId(), e);
}
}

@Override
public boolean deleteById(Long id) {
String sql = "DELETE FROM books WHERE id = ?";
try (PreparedStatement statement = ConnectionUtil.getConnection().prepareStatement(sql)) {
statement.setLong(1, id);
return statement.executeUpdate() > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can't delete book with id = " + id, e);
}
}

private Book getBook(ResultSet resultSet) throws SQLException {
Long id = resultSet.getObject("id", Long.class);
Integer price = resultSet.getObject("price", Integer.class);
String title = resultSet.getString("title");
return new Book(id, title, price);
}
}
11 changes: 11 additions & 0 deletions src/main/java/mate/academy/exception/DataProcessingException.java
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);
}
}
2 changes: 1 addition & 1 deletion src/main/java/mate/academy/lib/Dao.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Dao {
public @interface Dao {
}
47 changes: 47 additions & 0 deletions src/main/java/mate/academy/model/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package mate.academy.model;

public class Book {
private Long id;

private String title;
private int price;

public Book(Long id, String title, int 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 int getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

@Override
public String toString() {
return "Book{"
+ "id=" + id
+ ", title='" + title + '\''
+ ", price=" + price
+ '}';
}
}
16 changes: 16 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
CREATE DATABASE IF NOT EXISTS book DEFAULT CHARACTER SET utf8;

USE book;

CREATE TABLE IF NOT EXISTS Books (
id BIGINT AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
price int(10) NOT NULL,
PRIMARY KEY (id)
);

INSERT INTO Books (title, price) VALUES ('A Christmas Carol', 9);
INSERT INTO Books (title, price) VALUES ('1984', 11);
INSERT INTO Books (title, price) VALUES ('Don Quixote', 15);
INSERT INTO Books (title, price) VALUES ('Animal farm', 7);
INSERT INTO Books (title, price) VALUES ('War and Peace', 20);

0 comments on commit e137a1b

Please sign in to comment.