Skip to content

Commit

Permalink
create Book entity and implement BookDao repository interface
Browse files Browse the repository at this point in the history
  • Loading branch information
nikitaabo committed Aug 7, 2024
1 parent bc1d800 commit 0665cec
Show file tree
Hide file tree
Showing 9 changed files with 270 additions and 2 deletions.
8 changes: 8 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@
</maven.checkstyle.plugin.configLocation>
</properties>

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

<build>
<plugins>
<plugin>
Expand Down
28 changes: 28 additions & 0 deletions src/main/java/mate/academy/ConnectionUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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/ma_db";
private static final Properties DB_PROPERTIES;

static {
DB_PROPERTIES = new Properties();
DB_PROPERTIES.put("user", "bestuser");
DB_PROPERTIES.put("password", "bestuser");

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);
}
}
34 changes: 33 additions & 1 deletion src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,39 @@
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.models.Book;

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

public static void main(String[] args) {
System.out.println("Creating a new book:");
BookDao bookDao = (BookDao) injector.getInstance(BookDao.class);
Book book = new Book();
book.setTitle("Treasure Island");
book.setPrice(BigDecimal.valueOf(1500));
System.out.println(bookDao.create(book));
System.out.println("Getting book by id:");
Optional<Book> optionalBook = bookDao.findById(3L);
System.out.println(optionalBook.orElseThrow());
System.out.println("Getting all books:");
List<Book> books = bookDao.findAll();
for (Book row : books) {
System.out.println(row);
}
System.out.println("Book with id = 1 before updating:");
System.out.println(bookDao.findById(4L).orElseThrow());
System.out.println("Book with id = 1 after updating:");
Book updatedBook = new Book();
updatedBook.setId(4L);
updatedBook.setTitle("New title");
updatedBook.setPrice(BigDecimal.valueOf(2000));
System.out.println(bookDao.update(updatedBook));
System.out.println("Deleting book with id = 1:");
System.out.println(bookDao.deleteById(4L));
}
}
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 java.util.List;
import java.util.Optional;
import mate.academy.models.Book;

public interface BookDao {
Book create(Book book);

Optional<Book> findById(Long id);

List<Book> findAll();

Book update(Book book);

boolean deleteById(Long id);
}
118 changes: 118 additions & 0 deletions src/main/java/mate/academy/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
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.models.Book;

@Dao
public class BookDaoImpl implements BookDao {
@Override
public Book create(Book book) {
String sql = "INSERT INTO books (title, price) VALUES (?,?)";
Throwable ex = null;
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, book.getTitle());
statement.setObject(2, book.getPrice());
int affectedRows = statement.executeUpdate();
if (affectedRows < 1) {
throw new DataProcessingException("Expected to insert at least one row, "
+ "but inserted 0 rows.", ex);
}
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", e);
}
return book;
}

@Override
public Optional<Book> findById(Long id) {
String sql = "SELECT * FROM books WHERE id = ?";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String title = resultSet.getString("title");
BigDecimal price = resultSet.getBigDecimal("price");
Book book = new Book();
book.setId(id);
book.setTitle(title);
book.setPrice(price);
return Optional.of(book);
}
} catch (SQLException e) {
throw new DataProcessingException("Can not find a book with ID: " + id, e);
}
return Optional.empty();
}

@Override
public List<Book> findAll() {
List<Book> books = new ArrayList<>();
String sql = "SELECT * FROM books";
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Book book = new Book();
book.setId(resultSet.getLong(1));
book.setTitle(resultSet.getString(2));
book.setPrice(resultSet.getBigDecimal(3));
books.add(book);
}
} catch (SQLException e) {
throw new DataProcessingException("Can't get books", e);
}
return books;
}

@Override
public Book update(Book book) {
String sql = "UPDATE books SET title = ?, price = ? WHERE id = ?";
Throwable ex = null;
try (Connection connection = ConnectionUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(3, book.getId());
statement.setString(1, book.getTitle());
statement.setBigDecimal(2, book.getPrice());
int affectedRows = statement.executeUpdate();
if (affectedRows < 1) {
throw new DataProcessingException("Cannot update a book with ID: " + book.getId(),
ex);
}
} catch (SQLException e) {
throw new DataProcessingException("Can't get the books", 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);
int affectedRows = statement.executeUpdate();
return affectedRows > 0;
} catch (SQLException e) {
throw new DataProcessingException("Can't delete book with ID: " + id, e);
}
}
}
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);
}
}
10 changes: 9 additions & 1 deletion src/main/java/mate/academy/lib/Injector.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public class Injector {
private final List<Class<?>> classes = new ArrayList<>();

private Injector(String mainPackageName) {
System.out.println("Initializing Injector for package: " + mainPackageName);
try {
classes.addAll(getClasses(mainPackageName));
} catch (IOException | ClassNotFoundException e) {
Expand Down Expand Up @@ -73,6 +74,7 @@ private Object createInstance(Class<?> clazz) {
*/
private static List<Class<?>> getClasses(String packageName)
throws IOException, ClassNotFoundException {
System.out.println("Getting classes for package: " + packageName);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
throw new RuntimeException("Class loader is null");
Expand All @@ -82,7 +84,10 @@ private static List<Class<?>> getClasses(String packageName)
List<File> dirs = new ArrayList<>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
String decodedPath = java.net.URLDecoder.decode(resource.getFile(), "UTF-8");
System.out.println("Decoded Resource: " + decodedPath);
System.out.println("Resource: " + resource.getFile());
dirs.add(new File(decodedPath));
}
ArrayList<Class<?>> classes = new ArrayList<>();
for (File directory : dirs) {
Expand All @@ -103,8 +108,10 @@ private static List<Class<?>> findClasses(File directory, String packageName)
throws ClassNotFoundException {
List<Class<?>> classes = new ArrayList<>();
if (!directory.exists()) {
System.out.println("Directory does not exist: " + directory.getAbsolutePath());
return classes;
}
System.out.println("Scanning directory: " + directory.getAbsolutePath());
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
Expand All @@ -115,6 +122,7 @@ private static List<Class<?>> findClasses(File directory, String packageName)
classes.addAll(findClasses(file, packageName + "."
+ file.getName()));
} else if (file.getName().endsWith(".class")) {
System.out.println("Found class file: " + file.getName());
classes.add(Class.forName(packageName + '.'
+ file.getName().substring(0, file.getName().length() - 6)));
}
Expand Down
42 changes: 42 additions & 0 deletions src/main/java/mate/academy/models/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package mate.academy.models;

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

USE ma_db;

0 comments on commit 0665cec

Please sign in to comment.