Skip to content

Commit

Permalink
JDBC intro.
Browse files Browse the repository at this point in the history
  • Loading branch information
MukhailoVorobets committed Jul 21, 2024
1 parent bc1d800 commit 8080f29
Show file tree
Hide file tree
Showing 8 changed files with 244 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,28 @@
package mate.academy;

import java.math.BigDecimal;
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();
book.setTitle("BookTitle_1");
book.setPrice(BigDecimal.valueOf(100.00));

bookDao.create(book);
bookDao.findById(book.getId()).ifPresent(System.out::println);

book.setTitle("BookTitle_test");
book.setPrice(BigDecimal.valueOf(200.00));
bookDao.update(book);
bookDao.findAll().stream().forEach(System.out::println);

System.out.println(bookDao.deleteById(book.getId()));

}
}
18 changes: 18 additions & 0 deletions src/main/java/mate/academy/dao/BookDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
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);
}
116 changes: 116 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
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 books (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 DataProcessingException("Expected to insert at lest "
+ "one 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 add new book" + book,e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
String sql = "SELECT * FROM books WHERE id = ?";
Book book = null;
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
book = getBook(resultSet);
}
} catch (SQLException e) {
throw new DataProcessingException("Can not find bok by id: " + id, e);
}
return Optional.empty();
}

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

try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
books.add(getBook(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException("Can not get books from DB", e);
}
return books;
}

@Override
public Book update(Book book) {
String sql = "UPDATE books 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());
statement.executeUpdate();
} catch (SQLException e) {
throw new DataProcessingException("Can not update book: " + book, e);
}
return book;
}

@Override
public boolean deleteById(Long id) {
String sql = "DELETE FROM books WHERE id = ?";

try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, id);
return statement.executeUpdate() > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can not delete book where id: " + id,e);
}
}

private Book getBook(ResultSet resultSet) throws SQLException {
Long id = resultSet.getObject("id", Long.class);
String title = resultSet.getString("title");
BigDecimal price = resultSet.getObject("price", BigDecimal.class);
Book book = new Book();
book.setId(id);
book.setTitle(title);
book.setPrice(price);
return book;
}
}
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 massage) {
super(massage);
}

public DataProcessingException(String message, Throwable cause) {
super(message, cause);
}
}
3 changes: 3 additions & 0 deletions src/main/java/mate/academy/lib/Dao.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package mate.academy.lib;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Dao {
}
42 changes: 42 additions & 0 deletions src/main/java/mate/academy/model/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
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
+ '}';
}
}
26 changes: 26 additions & 0 deletions src/main/java/mate/academy/util/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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 DB_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", "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);
}
}
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 @@
DROP TABLE IF EXISTS books;

CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL
);

0 comments on commit 8080f29

Please sign in to comment.