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

added necessary methods #321

Open
wants to merge 2 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: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@
https://raw.githubusercontent.com/mate-academy/style-guides/master/java/checkstyle.xml
</maven.checkstyle.plugin.configLocation>
</properties>
<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>

<build>
<plugins>
Expand Down
26 changes: 26 additions & 0 deletions src/main/java/mate/academy/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package mate.academy;

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","DimaSlava");
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);
}
}
27 changes: 27 additions & 0 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,34 @@
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 {
private static final Injector injector = Injector.getInstance("mate.academy");

public static void main(String[] args) {
BookDao bookDao = (BookDao) injector.getInstance(BookDao.class);

Book bookJava = new Book();
bookJava.setTitle("Java");
bookJava.setPrice(BigDecimal.valueOf(350.00));
bookDao.create(bookJava);

Book bookHistory = new Book();
bookHistory.setTitle("History");
bookHistory.setPrice(BigDecimal.valueOf(350.00));
bookDao.create(bookHistory);

Optional<Book> optional = bookDao.findById(3L);
Book book = optional.get();
System.out.println(book);

List<Book> list = bookDao.findAll();
System.out.println(list);
bookDao.deleteById(1L);
}
}
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);
}
123 changes: 123 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
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.ConnectionUtil;
import mate.academy.exception.DataProcessingException;
import mate.academy.lib.Dao;
import mate.academy.model.Book;

@Dao
public class BookDaoImpl implements BookDao {
public static final int TITLE_INDEX = 1;
public static final int PRICE_INDEX = 2;
public static final int KEY_INDEX = 1;
public static final int KEY_POSITION_INDEX = 3;
public static final int MINIMUM_AFFECTED_ROWS = 1;
public static final int EXCEPTION_AFFECTED_ROWS = 0;
private static final String ID_COLUMN = "id";
private static final String TITLE_COLUMN = "title";
private static final String PRICE_COLUMN = "price";

@Override
public Book create(Book book) {
String createQuery = "INSERT INTO book(title,price) VALUE(?, ?)";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection
.prepareStatement(createQuery, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(TITLE_INDEX, book.getTitle());
statement.setBigDecimal(PRICE_INDEX,book.getPrice());
int affectedRows = statement.executeUpdate();
if (affectedRows < MINIMUM_AFFECTED_ROWS) {
throw new DataProcessingException("Expected to insert at least one row,"
+ " but inserted 0 rows",null);
}
ResultSet generateKeys = statement.getGeneratedKeys();
if (generateKeys.next()) {
long id = generateKeys.getObject(KEY_INDEX,long.class);
book.setId(id);
}
} catch (SQLException e) {
throw new DataProcessingException("Can not create new book: " + book, e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
String findByIdQuery = "SELECT * FROM book WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(findByIdQuery)) {
statement.setLong(KEY_INDEX,id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(parseBookFromResultSet(resultSet));
}
} catch (SQLException e) {
throw new DataProcessingException("Can't find all books", e);
}
return Optional.empty();
}

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
String findAllQuery = "SELECT * FROM book";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(findAllQuery)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
books.add(parseBookFromResultSet(resultSet));
}
return books;
} catch (SQLException e) {
throw new DataProcessingException("Failed to select all books form DB", e);
}
}

@Override
public Book update(Book book) {
String updateQuery = "UPDATE book SET title = ?, price = ? WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(updateQuery)) {
statement.setString(TITLE_INDEX, book.getTitle());
statement.setBigDecimal(PRICE_INDEX, book.getPrice());
statement.setLong(KEY_POSITION_INDEX, book.getId());
int affectedRows = statement.executeUpdate();
if (affectedRows == EXCEPTION_AFFECTED_ROWS) {
throw new RuntimeException("Updating book failed, no rows affected.");
Copy link

Choose a reason for hiding this comment

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

I'd also replace this ex to DataProcessingException

}
} catch (SQLException e) {
throw new DataProcessingException("Error updating book: " + book, e);
}
return book;
}

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

private Book parseBookFromResultSet(ResultSet resultSet) throws SQLException {
Book newBook = new Book();
newBook.setId(resultSet.getObject(ID_COLUMN, Long.class));
newBook.setTitle(resultSet.getObject(TITLE_COLUMN, String.class));
newBook.setPrice(resultSet.getObject(PRICE_COLUMN, BigDecimal.class));
Comment on lines +119 to +120
Copy link

Choose a reason for hiding this comment

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

in the case of String and BigDecimal, it is actually fine to use getString() and .getBigDecimal() because it is already an object, when with case of getLong() it returns a primitive(which can not be null) and thus we have to use getObject() instead.
It's fine to leave it as it is, just wanted you to know 😉

return newBook;
}
}
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);
}
}
45 changes: 45 additions & 0 deletions src/main/java/mate/academy/model/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
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
+
'}';
}
}

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 `book`(
`id` BIGINT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255),
`price` DECIMAL(10, 2),
PRIMARY KEY(`id`)
);
Loading