Skip to content
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

jdbc hw is done #82

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.1.0</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
Expand Down
21 changes: 20 additions & 1 deletion src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
package mate.academy;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
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 dao = (BookDao) injector.getInstance(BookDao.class);
Book book = new Book();
book.setTitle("Hobbit");
book.setPrice(new BigDecimal("630.35"));
dao.create(book);
Optional<Book> bookGet = dao.findById(1L);
List<Book> books = dao.findAll();
book.setPrice(BigDecimal.valueOf(5000.50));
dao.update(book);
System.out.println(book);
dao.deleteById(1L);
}
}
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.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.exception.DataProcessingException;
import mate.academy.lib.Dao;
import mate.academy.model.Book;
import mate.academy.util.ConnectionUtil;

@Dao
public class BookDaoImpl implements BookDao {
@Override
public Book create(Book book) {
String sql = "INSERT INTO book (title, price) VALUES (?, ?)";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(
sql, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());

int affectedRows = statement.executeUpdate();
if (affectedRows < 1) {
throw new RuntimeException("Expected to add 1 row, but inserted 0 rows");
}

ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
Long id = generatedKeys.getObject(1, Long.class);
book.setId(id);
}
} 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 book WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, id);
ResultSet result = statement.executeQuery();
if (result.next()) {
Book book = parse(result);
return Optional.of(book);
}
} catch (SQLException e) {
throw new DataProcessingException("Cant find book by id:" + id, e);
}
return Optional.empty();
}

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
String sql = "SELECT * FROM book";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Book book = parse(resultSet);
books.add(book);
}
return books;
} catch (SQLException e) {
throw new DataProcessingException("Cant find all books in db", e);
}
}

@Override
public Book update(Book book) {
String sql = "UPDATE book SET title = ?, price = ? WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
statement.setLong(3, book.getId());

int affectedRows = statement.executeUpdate();
if (affectedRows < 1) {
throw new RuntimeException("Expected to add 1 row, but inserted 0 rows");
}
} catch (SQLException e) {
throw new DataProcessingException("Cant update book by id:" + book.getId(), e);
}
return null;
}

@Override
public boolean deleteById(Long id) {
String sql = "DELETE FROM book WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, id);
int affectedRows = statement.executeUpdate();
return affectedRows > 0;
} catch (SQLException e) {
throw new DataProcessingException("Cant delete book by id:" + id, e);
}
}

private Book parse(ResultSet resultSet) throws SQLException {
Long id = resultSet.getObject("id", Long.class);
String title = resultSet.getString("title");
BigDecimal price = resultSet.getBigDecimal("price");
Book book = new Book();
book.setId(id);
book.setPrice(price);
book.setTitle(title);
return book;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package mate.academy.exception;

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

import java.math.BigDecimal;

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

public Long getId() {
return id;
}

public String getTitle() {
return title;
}

public BigDecimal getPrice() {
return 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;
}

@Override
public String toString() {
return "Book {"
+ "id = "
+ id + ", title = '"
+ title + '\''
+ ", price = "
+ price + '}';
}
}
28 changes: 28 additions & 0 deletions src/main/java/mate/academy/util/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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 DR_NAME = "com.mysql.cj.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/book_db";
private static final Properties DB_PROPERTIES;

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

try {
Class.forName(DR_NAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Can't load JDBC driver", e);
}
}

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL, DB_PROPERTIES);
}
}
12 changes: 12 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
CREATE DATABASE `book_db` DEFAULT CHARACTER SET utf8;

USE book_db;

CREATE TABLE `book`
(
`id` BIGINT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`price` DECIMAL(10, 2) NOT NULL,
PRIMARY KEY (`id`)
);

Loading