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-v1 #349

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
17 changes: 17 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@
<artifactId>jv-jdbc-intro</artifactId>
<version>1.0-SNAPSHOT</version>

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

<properties>
<jdk.version>17</jdk.version>
<maven.compiler.source>17</maven.compiler.source>
Expand Down Expand Up @@ -39,6 +47,15 @@
<linkXRef>false</linkXRef>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>22</source>
<target>22</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
Expand Down
25 changes: 25 additions & 0 deletions 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.Optional;
import mate.academy.dao.BookDao;
import mate.academy.dao.BookDaoImpl;
import mate.academy.lib.Injector;
import mate.academy.model.Book;

private static final Injector injector = Injector.getInstance("mate.academy");
public class Main {
public static void main(String[] args) {

Choose a reason for hiding this comment

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

Suggested change
public static void main(String[] args) {
private static final Injector injector = Injector.getInstance("mate.academy");
public static void main(String[] args) {

BookDaoImpl bookDao = (BookDaoImpl) injector.getInstance(BookDao.class);

Book book = new Book();
book.setId(1L);
book.setTitle("Frodo and stuff");
book.setPrice(new BigDecimal(100));
bookDao.create(book);

Optional<Book> foundBook = bookDao.findById(book.getId());
foundBook.ifPresent(System.out::println);

book.setTitle("Eldery stuff");
bookDao.update(book);

bookDao.deleteById(1L);

bookDao.findAll().forEach(System.out::println);
}
}

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

import java.util.List;
import java.util.Optional;
import mate.academy.lib.Dao;
import mate.academy.model.Book;

@Dao

Choose a reason for hiding this comment

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

Suggested change
@Dao

This annotation shouldn't be here

public interface BookDao {
Book create(Book book);

List<Book> findAll();

Optional<Book> findById(Long id);

Book update(Book book);

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

import java.sql.Connection;
import java.sql.DriverManager;
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.lib.Dao;
import mate.academy.model.Book;

@Dao
public class BookDaoImpl implements BookDao {
public static final String URL = "jdbc:mysql://localhost:3306/book";
public static final String USER = "root";
public static final String PASSWORD = "1111";

@Override
public Book create(Book book) {
String query = "INSERT INTO books (title, price) VALUES (?, ?)";
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {

Choose a reason for hiding this comment

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

Let's create ConnectionUtil in util package for create connection and provide driver and properties. Suggest to rewatch video "How to create connection" from the topic

Choose a reason for hiding this comment

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

Please, pay attention to the comment

PreparedStatement preparedStatement =

Choose a reason for hiding this comment

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

PreparedStatement also can be declare in try ()

Choose a reason for hiding this comment

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

Please, pay attention to the comment

connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, book.getTitle());
preparedStatement.setBigDecimal(2, book.getPrice());
int updatedRows = preparedStatement.executeUpdate();
if (updatedRows == 0) {

Choose a reason for hiding this comment

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

Suggested change
if (updatedRows == 0) {
if (updatedRows < 1) {

Choose a reason for hiding this comment

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

Not fixed

throw new RuntimeException("Creating book failed, no rows affected.");
}
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
book.setId(generatedKeys.getLong(1));

Choose a reason for hiding this comment

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

Suggested change
book.setId(generatedKeys.getLong(1));
book.setId(generatedKeys.getObject(1, Long.class));

see checklist file

Choose a reason for hiding this comment

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

Not fixed

}
} catch (RuntimeException e) {
throw new RuntimeException("Runtime exception while creating book."
+ " Can't create book", e);
} catch (SQLException e) {
throw new RuntimeException("SQL error while creating book."
+ " Can't create book", e);
}
return book;
}

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
String query = "SELECT * FROM books";
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
Statement statement = connection.createStatement();

Choose a reason for hiding this comment

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

Use PreparedStatement over Statement, even for a static query with no parameters in findAll() method. It's the best practice, and it's slightly faster.

see checklist file

Choose a reason for hiding this comment

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

Not fixed

ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()) {
books.add(mapBookFromResultSet(resultSet));
}
} catch (SQLException e) {
throw new RuntimeException("SQL error while creating book. Can't find book", e);
}
return books;
}

@Override
public Optional<Book> findById(Long id) {
String query = "SELECT * FROM books WHERE id = ?";
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setLong(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return Optional.of(mapBookFromResultSet(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't find a book by id: " + id, e);;
}
return Optional.empty();
}

@Override
public Book update(Book book) {
String query = "UPDATE books SET title = ?, price = ? WHERE id = ?";
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, book.getTitle());
preparedStatement.setBigDecimal(2, book.getPrice());
preparedStatement.setLong(3, book.getId());
if (preparedStatement.executeUpdate() > 0) {
return book;
}
} catch (SQLException e) {
throw new RuntimeException("Sql error while updating book",e);
}
throw new RuntimeException("Book not found");
}

@Override
public boolean deleteById(Long id) {
String query = "DELETE FROM books WHERE id = ?";
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setLong(1, id);
return preparedStatement.executeUpdate() > 0;
} catch (SQLException e) {
throw new RuntimeException("Sql error while deleting book",e);
}
}

private Book mapBookFromResultSet(ResultSet resultSet) {
try {
Book book = new Book();
book.setId(resultSet.getLong("id"));
book.setTitle(resultSet.getString("title"));
book.setPrice(resultSet.getBigDecimal("price"));
return book;
} catch (SQLException e) {
throw new RuntimeException("SQL error while mapping - can't return book.", e);
}
}
}
38 changes: 38 additions & 0 deletions src/main/java/mate/academy/model/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
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 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/inint_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) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
PRIMARY KEY (id)
);
Loading