Skip to content

Commit

Permalink
added jv-jdbc-intro solution
Browse files Browse the repository at this point in the history
  • Loading branch information
fmIst0 committed Aug 2, 2023
1 parent ee3ea7f commit 6d680f5
Show file tree
Hide file tree
Showing 8 changed files with 296 additions and 1 deletion.
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,11 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</project>
27 changes: 26 additions & 1 deletion src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,32 @@
package mate.academy;

import java.math.BigDecimal;
import java.util.ArrayList;
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");
private static final BookDao bookDao =
(BookDao) injector.getInstance(BookDao.class);
public static void main(String[] args) {

Book book1 = new Book(1L, "Math", BigDecimal.valueOf(100));
Book book2 = new Book(2L, "Java", BigDecimal.valueOf(150));
List<Book> books = new ArrayList<>();
books.add(book1);
books.add(book2);
// for (Book book : books) {
// bookDao.create(book);
// } // success
System.out.println(bookDao.findAll());
System.out.println(bookDao.findById(1L));
book1.setTitle("English");
book1.setPrice(BigDecimal.valueOf(70));
bookDao.update(book1);
bookDao.deleteById(1L);
System.out.println(bookDao.findById(1L));
}
}
29 changes: 29 additions & 0 deletions src/main/java/mate/academy/connection/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package mate.academy.connection;

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/books_db";
private static final String USERNAME = "root";
private static final String PASSWORD = "12345678";
private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";

static {
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Can't find SQL Driver", e);
}
}

public static Connection getConnection() throws SQLException {
Properties dbProperties = new Properties();
dbProperties.setProperty("user", USERNAME);
dbProperties.setProperty("password", PASSWORD);
return DriverManager.getConnection(URL, dbProperties);
}
}
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.models.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/impl/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package mate.academy.dao.impl;

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.connection.ConnectionUtil;
import mate.academy.dao.BookDao;
import mate.academy.exceptions.DataProcessingException;
import mate.academy.lib.Dao;
import mate.academy.models.Book;

@Dao
public class BookDaoImpl implements BookDao {
@Override
public Book create(Book book) {
String query = "INSERT INTO books (title, price) "
+ "VALUES (?, ?);";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement =
connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
statement.executeUpdate();
ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet.next()) {
book.setId(resultSet.getObject(1, Long.class));
}
return book;
} catch (SQLException e) {
throw new DataProcessingException(
"Can't insert a book into DB: " + book, e
);
}
}

@Override
public Optional<Book> findById(Long id) {
String query = "SELECT * FROM books "
+ "WHERE id = ? AND is_deleted = FALSE;";
Book book = null;
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setLong(1, id);
statement.executeQuery();
ResultSet resultSet = statement.getResultSet();
if (resultSet.next()) {
book = getBookFromResultSet(resultSet);
}
} catch (SQLException e) {
throw new DataProcessingException(
"Can't get a book from DB by id: " + id, e
);
}
return Optional.ofNullable(book);
}

@Override
public List<Book> findAll() {
String query = "SELECT * FROM books WHERE is_deleted = FALSE;";
List<Book> books = new ArrayList<>();
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.executeQuery();
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()) {
books.add(getBookFromResultSet(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException(
"Can't get all books from DB.", e
);
}
return books;
}

@Override
public Book update(Book book) {
String query = "UPDATE books SET title = ?, price = ? "
+ "WHERE is_deleted = FALSE AND id = ?;";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
statement.setLong(3, book.getId());
statement.executeUpdate();
} catch (SQLException e) {
throw new DataProcessingException(
"Can't update a book in DB.", e
);
}
return book;
}

@Override
public boolean deleteById(Long id) {
String query = "UPDATE books SET is_deleted = TRUE WHERE id = ?;";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setLong(1, id);
return statement.executeUpdate() > 0;
} catch (SQLException e) {
throw new DataProcessingException(
"Can't delete a book from DB by id: " + id, e
);
}
}

private Book getBookFromResultSet(ResultSet resultSet) throws SQLException {
Long bookId = resultSet.getObject("id", Long.class);
String bookTitle = resultSet.getString("title");
BigDecimal bookPrice = resultSet.getBigDecimal("price");
return new Book(bookId, bookTitle, bookPrice);
}
}
15 changes: 15 additions & 0 deletions src/main/java/mate/academy/exceptions/DataProcessingException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package mate.academy.exceptions;

public class DataProcessingException extends RuntimeException {
public DataProcessingException() {

}

public DataProcessingException(String message) {
super(message);
}

public DataProcessingException(String message, Throwable ex) {
super(message, ex);
}
}
74 changes: 74 additions & 0 deletions src/main/java/mate/academy/models/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package mate.academy.models;

import java.math.BigDecimal;
import java.util.Objects;

public class Book {
private Long id;
private String title;
private BigDecimal price;

public Book() {
}

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 boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Book that = (Book) o;
return Objects.equals(id, that.id)
&& Objects.equals(title, that.title)
&& Objects.equals(price, that.price);
}

@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (price != null ? price.hashCode() : 0);
return result;
}

@Override
public String toString() {
return "Book{"
+ "id=" + id
+ ", title='" + title + '\''
+ ", price=" + price
+ '}';
}
}
8 changes: 8 additions & 0 deletions src/main/resources/inti_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE DATABASE `books_db` /*!40100 DEFAULT CHARACTER SET utf8mb3 */ /*!80016 DEFAULT ENCRYPTION='N' */;

CREATE TABLE `books_db`.`books` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`price` DECIMAL NOT NULL DEFAULT 0,
`is_deleted` TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (`id`));

0 comments on commit 6d680f5

Please sign in to comment.