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-intro #399

Open
wants to merge 3 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
7 changes: 0 additions & 7 deletions src/main/java/mate/academy/Main.java

This file was deleted.

36 changes: 36 additions & 0 deletions src/main/java/mate/academy/util/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package mate.academy.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionUtil {
private static final String PROPERTIES_FILE_PATH = "src/main/resources/db.properties";
private static final String DATABASE_URL = "db.url";
private static final String DATABASE_USER_NAME = "db.username";
private static final String DATABASE_USER_PASSWORD = "db.password";
private static final Properties properties = new Properties();

static {
readDatabaseFileProperties();
}

private static final void readDatabaseFileProperties() {
try (InputStream inputStreamProperties = new FileInputStream(PROPERTIES_FILE_PATH)) {
properties.load(inputStreamProperties);
} catch (IOException e) {
throw new RuntimeException("Cannot read properties file", e);
}
}

public static Connection connectToDatabase() throws SQLException {
String url = properties.getProperty(DATABASE_URL);
String username = properties.getProperty(DATABASE_USER_NAME);
String password = properties.getProperty(DATABASE_USER_PASSWORD);
return DriverManager.getConnection(url, username, password);
}
}
21 changes: 21 additions & 0 deletions src/main/java/mate/academy/util/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package mate.academy.util;

import java.math.BigDecimal;
import mate.academy.util.dao.BookDao;
import mate.academy.util.domain.Book;
import mate.academy.util.lib.Injector;

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);
Book book = new Book("The witcher", new BigDecimal("195.00"));
bookDao.create(book);
bookDao.create(book);
bookDao.update(book);
bookDao.deleteById(1);
bookDao.findAll();
bookDao.findById(2);
}
}
17 changes: 17 additions & 0 deletions src/main/java/mate/academy/util/dao/BookDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package mate.academy.util.dao;

import java.util.List;
import java.util.Optional;
import mate.academy.util.domain.Book;

public interface BookDao {
Book create(Book book);

Optional<Book> findById(int id);

List<Book> findAll();

Book update(Book book);

boolean deleteById(int id);
}
135 changes: 135 additions & 0 deletions src/main/java/mate/academy/util/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package mate.academy.util.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.util.ConnectionUtil;
import mate.academy.util.domain.Book;
import mate.academy.util.exception.DataProcessingException;
import mate.academy.util.lib.Dao;

@Dao
public class BookDaoImpl implements BookDao {
private static final String CREATE_BOOK_QUERY = "INSERT INTO book (id, title, price) "
+ "VALUES (?, ?, ?)";
private static final String FIND_BOOK_BY_ID_QUERY = "SELECT * FROM book WHERE id = ?";
private static final String FIND_ALL_BOOK_QUERY = "SELECT * FROM book";
private static final String UPDATE_BOOK_QUERY = "UPDATE book SET title = ?, "
+ "price = ? WHERE id = ?";
private static final String DELETE_BOOK_QUERY = "DELETE FROM book WHERE id = ?";

@Override
public Book create(Book book) {
try (Connection connection = ConnectionUtil.connectToDatabase();
PreparedStatement preparedStatement = connection.prepareStatement(CREATE_BOOK_QUERY,
Statement.RETURN_GENERATED_KEYS)) {
preparedStatement.setLong(1, book.getId());
preparedStatement.setString(2, book.getTitle());
preparedStatement.setBigDecimal(3, book.getPrice());
preparedStatement.execute();
int affectedRows = preparedStatement.executeUpdate();
if (affectedRows < 1) {
throw new DataProcessingException(
"Expected to insert at least 1 row, but was 0");
}
try (ResultSet generatedKeys = preparedStatement.getGeneratedKeys()) {
if (generatedKeys.next()) {
Long id = generatedKeys.getObject(1, Long.class);
book.setId(id);
}
}
} catch (SQLException e) {
throw new DataProcessingException("Can't add a new book" + book, e);
}
return book;
}

@Override
public Optional<Book> findById(int id) {
Optional<Book> findBookById = Optional.empty();
try (Connection connection = ConnectionUtil.connectToDatabase();
PreparedStatement preparedStatement =
connection.prepareStatement(FIND_BOOK_BY_ID_QUERY)) {
preparedStatement.setLong(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
findBookById = Optional.of(mapResutSetToBook(resultSet, id));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't find book by id" + id, e);
}
return findBookById;
}

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
try (Connection connection = ConnectionUtil.connectToDatabase();
PreparedStatement preparedStatement =
connection.prepareStatement(FIND_ALL_BOOK_QUERY)) {

ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Long bookId = resultSet.getLong("id");
books.add(mapResutSetToBook(resultSet, bookId));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't find all books", e);
}
return books;
}

@Override
public Book update(Book book) {
Book updatedBook = book;
try (Connection connection =
ConnectionUtil.connectToDatabase();
PreparedStatement preparedStatement =
connection.prepareStatement(UPDATE_BOOK_QUERY)) {
preparedStatement.setLong(1, book.getId());
preparedStatement.setString(2, book.getTitle());
preparedStatement.setBigDecimal(3, book.getPrice());
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String title = resultSet.getString("title");
BigDecimal price = resultSet.getBigDecimal("price");
updatedBook.setTitle(title);
updatedBook.setPrice(price);
}
} catch (SQLException e) {
throw new DataProcessingException("Can't update book: " + book, e);
}
return updatedBook;
}

@Override
public boolean deleteById(int id) {
try (Connection connection = ConnectionUtil.connectToDatabase();
PreparedStatement preparedStatement =
connection.prepareStatement(DELETE_BOOK_QUERY)) {
preparedStatement.setLong(1, id);
return preparedStatement.executeUpdate() > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can't delete book by id: " + id, e);
}
}

private Book mapResutSetToBook(ResultSet resultSet, long id) {
Book book;
try {
String title = resultSet.getString("title");
BigDecimal price = resultSet.getBigDecimal("price");
book = new Book(id, title, price);
} catch (SQLException e) {
throw new DataProcessingException("Can't map result set to book: " + resultSet, e);
}
return book;
}
}

60 changes: 60 additions & 0 deletions src/main/java/mate/academy/util/domain/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package mate.academy.util.domain;

import java.math.BigDecimal;

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

public Book() {
}

public Book(String title, BigDecimal price) {
this.title = title;
this.price = price;
}

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 String toString() {
return "Book{"
+ "id="
+ id
+ ", title='"
+ title
+ '\''
+ ", price="
+ price
+ '}';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.util.exception;

public class DataProcessingException extends RuntimeException {
public DataProcessingException(String message) {
super(message);
}

public DataProcessingException(String message, Throwable cause) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package mate.academy.lib;
package mate.academy.util.lib;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package mate.academy.lib;
package mate.academy.util.lib;

import java.io.File;
import java.io.IOException;
Expand Down
3 changes: 3 additions & 0 deletions src/main/resources/db.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
db.url=jdbc:mysql://localhost:3307/test
db.username=
db.password=
7 changes: 7 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
create schema if not exists test;

create table if not exists book (
book_id bigint primary key,
title varchar(20),
price decimal
);
Loading