🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Java Persistence API (JPA) is a specification for managing relational data in Java applications. It provides a standard way to manage persistence and object-relational mapping (ORM) in Java. In this tutorial, we will demonstrate how to perform basic CRUD (Create, Read, Update, and Delete) operations using JPA with Hibernate implementation and EntityManager.
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 JPA Project
1.1 Create a Maven Project
-
Open your IDE and create a new Maven project.
-
Configure the
pom.xmlfile 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>jpa-hibernate-crud</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- JPA and Hibernate -->
<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="PERSISTENCE">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.example.jpa.hibernate.crud.model.Employee</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 an Employee class in the com.example.jpa.hibernate.crud.model package:
package com.example.jpa.hibernate.crud.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String department;
private double salary;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
Step 3: Creating the DAO Class
Create a DAO class to manage CRUD operations in the com.example.jpa.hibernate.crud.dao package:
package com.example.jpa.hibernate.crud.dao;
import com.example.jpa.hibernate.crud.model.Employee;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import java.util.List;
public class EmployeeDao {
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("PERSISTENCE");
public void saveEmployee(Employee employee) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(employee);
em.getTransaction().commit();
em.close();
}
public void updateEmployee(Employee employee) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(employee);
em.getTransaction().commit();
em.close();
}
public Employee getEmployeeById(Long id) {
EntityManager em = emf.createEntityManager();
Employee employee = em.find(Employee.class, id);
em.close();
return employee;
}
public List<Employee> getAllEmployees() {
EntityManager em = emf.createEntityManager();
TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e", Employee.class);
List<Employee> employees = query.getResultList();
em.close();
return employees;
}
public void deleteEmployee(Long id) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Employee employee = em.find(Employee.class, id);
if (employee != null) {
em.remove(employee);
}
em.getTransaction().commit();
em.close();
}
}
Step 4: Creating the Main Class
Create a Main class in the com.example.jpa.hibernate.crud package to test the CRUD operations:
package com.example.jpa.hibernate.crud;
import com.example.jpa.hibernate.crud.dao.EmployeeDao;
import com.example.jpa.hibernate.crud.model.Employee;
import java.util.List;
public class Main {
public static void main(String[] args) {
EmployeeDao employeeDao = new EmployeeDao();
// Create and save a new employee
Employee employee = new Employee();
employee.setName("John Doe");
employee.setDepartment("IT");
employee.setSalary(60000);
employeeDao.saveEmployee(employee);
System.out.println("Employee saved.");
// Fetch and print all employees
List<Employee> employees = employeeDao.getAllEmployees();
employees.forEach(emp -> System.out.println(emp.getName() + " - " + emp.getDepartment() + " - " + emp.getSalary()));
// Update an employee
employee.setSalary(70000);
employeeDao.updateEmployee(employee);
System.out.println("Employee updated.");
// Fetch and print the updated employee
Employee updatedEmployee = employeeDao.getEmployeeById(employee.getId());
System.out.println("Updated Employee: " + updatedEmployee.getName() + " - " + updatedEmployee.getDepartment() + " - " + updatedEmployee.getSalary());
// Delete an employee
employeeDao.deleteEmployee(updatedEmployee.getId());
System.out.println("Employee deleted.");
}
}
Conclusion
In this tutorial, we demonstrated how to perform basic CRUD operations using JPA with Hibernate as the JPA provider and EntityManager for transaction management. 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 JPA and Hibernate.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment