diff --git a/pom.xml b/pom.xml index 683e84ec..d6035896 100644 --- a/pom.xml +++ b/pom.xml @@ -55,4 +55,11 @@ + + + com.mysql + mysql-connector-j + 9.0.0 + + diff --git a/src/main/java/mate/academy/Main.java b/src/main/java/mate/academy/Main.java index 0058fbf9..c1f0b5b5 100644 --- a/src/main/java/mate/academy/Main.java +++ b/src/main/java/mate/academy/Main.java @@ -1,7 +1,50 @@ package mate.academy; +import java.math.BigDecimal; +import java.util.List; +import mate.academy.dao.BookDao; +import mate.academy.lib.Injector; +import mate.academy.models.Book; + public class Main { + private static final Injector injector = Injector.getInstance("mate.academy.dao"); + public static void main(String[] args) { + BookDao bookDao = (BookDao) injector.getInstance(BookDao.class); + + bookDao.create(new Book(1L, "Java Programming", new BigDecimal("1000.00"))); + bookDao.create(new Book(2L, "Effective Java", new BigDecimal("1500.00"))); + bookDao.create(new Book(3L, "Clean Code", new BigDecimal("2000.00"))); + bookDao.create(new Book(4L, "Head First Java", new BigDecimal("2500.00"))); + bookDao.create(new Book(5L, "Java Concurrency in Practice", new BigDecimal("3000.00"))); + + System.out.println("FULL list of books"); + List list = bookDao.findAll(); + for (Book book : list) { + System.out.println(book.getId() + " " + book.getTitle() + " " + book.getPrice()); + } + + System.out.println("\n" + "Finding book by index:" + list.get(0).getId()); + Book book1 = bookDao.findById(list.get(0).getId()) + .orElseThrow(() -> + new RuntimeException("Objects with the specified ID do not exist")); + System.out.println(book1.getId() + " " + book1.getTitle() + " " + book1.getPrice()); + + System.out.println("\n" + "Updating book by index:" + list.get(0).getId()); + bookDao.update(new Book(list.get(0).getId(), "Nikilen", new BigDecimal(100))); + + Book book2 = bookDao.findById(list.get(0).getId()) + .orElseThrow(() -> + new RuntimeException("Objects with the specified ID do not exist")); + + System.out.println(book2.getId() + " " + book2.getTitle() + " " + book2.getPrice()); + + System.out.println("\n" + "Deleting an object by index:" + list.get(0).getId()); + if (bookDao.deleteById(list.get(0).getId())) { + System.out.println("The object is deleted"); + } else { + System.out.println("The object does not exist"); + } } } diff --git a/src/main/java/mate/academy/dao/BookDao.java b/src/main/java/mate/academy/dao/BookDao.java new file mode 100644 index 00000000..b47ae78f --- /dev/null +++ b/src/main/java/mate/academy/dao/BookDao.java @@ -0,0 +1,17 @@ +package mate.academy.dao; + +import java.util.List; +import java.util.Optional; +import mate.academy.models.Book; + +public interface BookDao { + Book create(Book book); + + Optional findById(Long id); + + List findAll(); + + Book update(Book book); + + boolean deleteById(Long id); +} diff --git a/src/main/java/mate/academy/dao/BookDaoImpl.java b/src/main/java/mate/academy/dao/BookDaoImpl.java new file mode 100644 index 00000000..ebc2f6e1 --- /dev/null +++ b/src/main/java/mate/academy/dao/BookDaoImpl.java @@ -0,0 +1,135 @@ +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.exceptions.DataProcessingException; +import mate.academy.lib.Dao; +import mate.academy.models.Book; +import mate.academy.util.ConnectionUtil; + +@Dao +public class BookDaoImpl implements BookDao { + @Override + public Book create(Book book) { + String sqlCommand = "INSERT INTO books (title,price) VALUE (?,?)"; + + try (Connection connection = ConnectionUtil.getConnection(); + PreparedStatement preparedStatement = + connection.prepareStatement(sqlCommand, Statement.RETURN_GENERATED_KEYS)) { + + preparedStatement.setString(1, book.getTitle()); + preparedStatement.setBigDecimal(2, book.getPrice()); + + int affectedRows = preparedStatement.executeUpdate(); + if (affectedRows < 1) { + throw new DataProcessingException("None of the rows have been added"); + } + + try (ResultSet generatedKeys = preparedStatement.getGeneratedKeys()) { + if (generatedKeys.next()) { + long id = generatedKeys.getObject(1, Long.class); + book.setId(id); + return book; + } else { + throw new DataProcessingException("Failed to retrieve the generated key"); + } + } + } catch (SQLException e) { + throw new DataProcessingException("Can't add a book", e); + } + } + + @Override + public Optional findById(Long id) { + String sqlCommand = "SELECT * FROM books WHERE id = ?"; + + try (Connection connection = ConnectionUtil.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(sqlCommand)) { + preparedStatement.setLong(1, id); + + try (ResultSet resultSet = preparedStatement.executeQuery()) { + if (resultSet.next()) { + return Optional.of(getBookFromResultSet(resultSet)); + } + } + } catch (SQLException e) { + throw new DataProcessingException("Can't find book by id", e); + } + return Optional.empty(); + } + + @Override + public List findAll() { + String sqlCommand = "SELECT * FROM books"; + List result = new ArrayList<>(); + + try (Connection connection = ConnectionUtil.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(sqlCommand); + ResultSet resultSet = preparedStatement.executeQuery()) { + + while (resultSet.next()) { + result.add(getBookFromResultSet(resultSet)); + } + + } catch (SQLException e) { + throw new DataProcessingException("Can't find all books", e); + } + + return result; + } + + @Override + public Book update(Book book) { + String sqlCommand = "UPDATE books SET title=?, price=? WHERE id = ?"; + + try (Connection connection = ConnectionUtil.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(sqlCommand)) { + + preparedStatement.setString(1, book.getTitle()); + preparedStatement.setBigDecimal(2, book.getPrice()); + preparedStatement.setLong(3, book.getId()); + + int affectedRows = preparedStatement.executeUpdate(); + if (affectedRows < 1) { + throw new DataProcessingException("None of the rows have been updated"); + } + + return book; + + } catch (SQLException e) { + throw new DataProcessingException("Can't update book", e); + } + } + + @Override + public boolean deleteById(Long id) { + String sqlCommand = "DELETE FROM books WHERE id = ?"; + + try (Connection connection = ConnectionUtil.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(sqlCommand)) { + + preparedStatement.setLong(1, id); + + int affectedRows = preparedStatement.executeUpdate(); + return affectedRows > 0; + + } catch (SQLException e) { + throw new DataProcessingException("Can't delete book by id", e); + } + } + + private Book getBookFromResultSet(ResultSet resultSet) throws SQLException { + Long id = resultSet.getObject("id", Long.class); + String title = resultSet.getObject("title", String.class); + BigDecimal price = resultSet.getObject("price", BigDecimal.class); + + return new Book(id, title, price); + } +} diff --git a/src/main/java/mate/academy/exceptions/DataProcessingException.java b/src/main/java/mate/academy/exceptions/DataProcessingException.java new file mode 100644 index 00000000..ae3a0b25 --- /dev/null +++ b/src/main/java/mate/academy/exceptions/DataProcessingException.java @@ -0,0 +1,12 @@ +package mate.academy.exceptions; + +public class DataProcessingException extends RuntimeException { + public DataProcessingException(String message) { + super(message); + } + + public DataProcessingException(String message, Throwable cause) { + super(message, cause); + } +} + diff --git a/src/main/java/mate/academy/models/Book.java b/src/main/java/mate/academy/models/Book.java new file mode 100644 index 00000000..8d0f2a87 --- /dev/null +++ b/src/main/java/mate/academy/models/Book.java @@ -0,0 +1,39 @@ +package mate.academy.models; + +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 void setId(Long id) { + this.id = id; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public BigDecimal getPrice() { + return price; + } +} diff --git a/src/main/java/mate/academy/util/ConnectionUtil.java b/src/main/java/mate/academy/util/ConnectionUtil.java new file mode 100644 index 00000000..93151965 --- /dev/null +++ b/src/main/java/mate/academy/util/ConnectionUtil.java @@ -0,0 +1,22 @@ +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 URL = "jdbc:mysql://localhost:3306/test"; + private static final Properties DB_PROPERTIES; + + static { + DB_PROPERTIES = new Properties(); + DB_PROPERTIES.put("user", "root"); + DB_PROPERTIES.put("password", "henghfdf"); + } + + public static Connection getConnection() throws SQLException { + return DriverManager.getConnection(URL, DB_PROPERTIES); + } +} diff --git a/src/main/resources/init_db.sql b/src/main/resources/init_db.sql new file mode 100644 index 00000000..2c95d888 --- /dev/null +++ b/src/main/resources/init_db.sql @@ -0,0 +1,6 @@ +CREATE TABLE `books`( + `id` BIGINT AUTO_INCREMENT, + `title` VARCHAR(255), + `price` DECIMAL, + PRIMARY KEY (`id`) +); \ No newline at end of file