Book
entity.Prerequisites
Before we start, ensure you have the following:
- Java Development Kit (JDK) installed
- Apache Maven installed
- MySQL database installed and running (or any other relational database)
- An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed
Step 1: Setting Up the Project
1.1 Create a Maven Project
-
Open your IDE and create a new Maven project.
-
Configure the
pom.xml
file with the following content:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>hibernate-crud-example</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Hibernate and JPA -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.0.Final</version>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- SLF4J for logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.32</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.32</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.2 Configure Hibernate
Create a persistence.xml
file in the src/main/resources/META-INF
directory with the following content:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence" version="3.0">
<persistence-unit name="examplePU">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.example.hibernatecrud.model.Book</class>
<properties>
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/your_database_name"/>
<property name="jakarta.persistence.jdbc.user" value="your_username"/>
<property name="jakarta.persistence.jdbc.password" value="your_password"/>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Replace your_database_name
, your_username
, and your_password
with your MySQL database credentials.
Step 2: Creating the Entity Class
Create a Book
class in the com.example.hibernatecrud.model
package:
package com.example.hibernatecrud.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
// Getters and Setters
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 String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Step 3: Creating the DAO Class
Create a DAO class to manage CRUD operations in the com.example.hibernatecrud.dao
package:
package com.example.hibernatecrud.dao;
import com.example.hibernatecrud.model.Book;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import java.util.List;
public class BookDao {
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("examplePU");
public void saveBook(Book book) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(book);
em.getTransaction().commit();
em.close();
}
public void updateBook(Book book) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(book);
em.getTransaction().commit();
em.close();
}
public Book getBookById(Long id) {
EntityManager em = emf.createEntityManager();
Book book = em.find(Book.class, id);
em.close();
return book;
}
public List<Book> getAllBooks() {
EntityManager em = emf.createEntityManager();
TypedQuery<Book> query = em.createQuery("SELECT b FROM Book b", Book.class);
List<Book> books = query.getResultList();
em.close();
return books;
}
public void deleteBook(Long id) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Book book = em.find(Book.class, id);
if (book != null) {
em.remove(book);
}
em.getTransaction().commit();
em.close();
}
}
Step 4: Creating the Main Class
Create a Main
class in the com.example.hibernatecrud
package to test the CRUD operations:
package com.example.hibernatecrud;
import com.example.hibernatecrud.dao.BookDao;
import com.example.hibernatecrud.model.Book;
import java.util.List;
public class Main {
public static void main(String[] args) {
BookDao bookDao = new BookDao();
// Create and save a new book
Book book = new Book();
book.setTitle("Hibernate in Action");
book.setAuthor("Gavin King");
book.setPrice(49.99);
bookDao.saveBook(book);
System.out.println("Book saved.");
// Fetch and print all books
List<Book> books = bookDao.getAllBooks();
books.forEach(b -> System.out.println(b.getTitle() + " - " + b.getAuthor() + " - " + b.getPrice()));
// Update a book
book.setPrice(39.99);
bookDao.updateBook(book);
System.out.println("Book updated.");
// Fetch and print the updated book
Book updatedBook = bookDao.getBookById(book.getId());
System.out.println("Updated Book: " + updatedBook.getTitle() + " - " + updatedBook.getAuthor() + " - " + updatedBook.getPrice());
// Delete a book
bookDao.deleteBook(updatedBook.getId());
System.out.println("Book deleted.");
}
}
Conclusion
In this tutorial, we demonstrated how to perform basic CRUD operations using Hibernate 6.4 with a Book
entity. We configured the project with Maven, set up Hibernate and JPA, created an entity class, a DAO class, and a main class to test the CRUD operations. By following these steps, you can effectively manage data persistence in your Java applications using Hibernate and JPA.
Comments
Post a Comment
Leave Comment