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 Solution #30

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 @@ -14,4 +14,12 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.1.0</version>
</dependency>
</dependencies>

</project>
31 changes: 31 additions & 0 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,38 @@
package mate.academy;

import mate.academy.dao.BookDao;
import mate.academy.lib.Injector;
import mate.academy.model.Book;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

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 marquezBook = new Book("One Hundred Years of Solitude", new BigDecimal(571));
Book rowlingBook = new Book(5L, "Harry Potter and the Half-Blood Prince", new BigDecimal(250));
Book secondMarquezBook = new Book(2L, "No One Writes to the Colonel", new BigDecimal(450));

// Book bookUpdated = bookDao.create(marquezBook);
// Book bookUpdated2 = bookDao.create(rowlingBook);
// System.out.println(bookUpdated);
// System.out.println(bookUpdated2);
//
// Optional<Book> bookById = bookDao.findById(3L);
// System.out.println(bookById);
//
// List<Book> allBooks = bookDao.findAll();
// for (Book element : allBooks) {
// System.out.println(element);
// }
//
// Book updateBook = bookDao.update(rowlingBook);
// System.out.println(updateBook);
Comment on lines +19 to +33

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just forgot to uncomment


boolean deleteBook = bookDao.deleteById(4L);
System.out.println(deleteBook);
}
}
28 changes: 28 additions & 0 deletions src/main/java/mate/academy/connection/util/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package mate.academy.connection.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;
private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String JDBC_DRIVER_EXCEPTION = "Cannot load JDBC driver";

static {
DB_PROPERTIES = new Properties();
DB_PROPERTIES.put("user", "root");
DB_PROPERTIES.put("password", "Root1234");
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
throw new RuntimeException(JDBC_DRIVER_EXCEPTION, e);
}
}

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL, DB_PROPERTIES);
}
}
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 mate.academy.model.Book;
import java.util.List;
import java.util.Optional;

public interface BookDao {
Book create(Book book);

Optional<Book> findById(Long id);

List<Book> findAll();

Book update(Book book);

boolean deleteById(Long id);
}
107 changes: 107 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package mate.academy.dao;

import mate.academy.connection.util.ConnectionUtil;
import mate.academy.exception.DataProcessingException;
import mate.academy.lib.Dao;
import mate.academy.model.Book;
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;

@Dao
public class BookDaoImpl implements BookDao {
private static final int AT_LEAST_ONE = 0;

@Override
public Book create(Book book) {
String sqlUpdate = "INSERT INTO books (title, price) VALUES (?, ?)";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sqlUpdate, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
Long id = generatedKeys.getObject(1, Long.class);
book.setId(id);
}
return book;
} catch (SQLException e) {
throw new DataProcessingException("Cannot add new book: " + book, e);
}
}

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

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
String sqlQuery = "SELECT * FROM books";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sqlQuery)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
books.add(parseBook(resultSet));
}
return books;
} catch (SQLException e) {
throw new DataProcessingException("Cannot get books", e);
}
}

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

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

private Book parseBook(ResultSet resultSet) throws SQLException {
Long id = resultSet.getObject("id", Long.class);
String model = resultSet.getString("title");
BigDecimal price = resultSet.getObject("price", BigDecimal.class);
return new Book(id, model, price);
}
}
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 ex) {
super(message, ex);
}
}
53 changes: 53 additions & 0 deletions src/main/java/mate/academy/model/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package mate.academy.model;

import java.math.BigDecimal;

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

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 +
'}';
}
}
6 changes: 6 additions & 0 deletions src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CREATE TABLE `books` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255),
`price` INT,
PRIMARY KEY (`id`)
);
Loading