Using JPA and Hibernate for ORM
ORM (Object–Relational Mapping) allows developers to map Java objects to database tables, eliminating the need to write most SQL queries manually.
JPA (Java Persistence API) is a specification that defines how ORM should work in Java, while Hibernate is the most popular implementation of JPA.
JPA vs Hibernate
Aspect JPA Hibernate
Type Specification ORM Framework
Purpose Defines standard ORM APIs Implements JPA + extra features
Portability High (vendor-neutral) Hibernate-specific features
Usage Interfaces & annotations Concrete implementation
๐ In practice, you code to JPA and run on Hibernate.
Key JPA Concepts
Entity
A Java class mapped to a database table.
EntityManager
Manages persistence operations (CRUD).
Persistence Unit
Configuration defining database connection and ORM settings.
JPQL
Object-oriented query language (works on entities, not tables).
Project Setup (Maven Example)
<dependencies>
<!-- JPA API -->
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- Hibernate ORM -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.0.Final</version>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>
Entity Mapping Example
import jakarta.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(unique = true)
private String email;
// getters and setters
}
Persistence Configuration (persistence.xml)
<persistence xmlns="https://jakarta.ee/xml/ns/persistence" version="3.0">
<persistence-unit name="myPU">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="jakarta.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/mydatabase"/>
<property name="jakarta.persistence.jdbc.user" value="root"/>
<property name="jakarta.persistence.jdbc.password" value="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"/>
</properties>
</persistence-unit>
</persistence>
CRUD Operations Using JPA
Create
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("myPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
User user = new User();
user.setName("Alice");
user.setEmail("alice@example.com");
em.persist(user);
em.getTransaction().commit();
Read
User user = em.find(User.class, 1L);
System.out.println(user.getName());
Update
em.getTransaction().begin();
user.setName("Alice Updated");
em.getTransaction().commit();
Delete
em.getTransaction().begin();
em.remove(user);
em.getTransaction().commit();
JPQL Example
List<User> users = em.createQuery(
"SELECT u FROM User u WHERE u.email LIKE :email", User.class)
.setParameter("email", "%@example.com")
.getResultList();
✔ Database-independent
✔ Works on entity attributes, not columns
Hibernate-Specific Features
Automatic dirty checking
Lazy loading
Second-level cache
Criteria API
Native SQL support
Example (Hibernate Session API):
Session session = em.unwrap(Session.class);
Best Practices
Prefer JPA annotations over Hibernate-specific ones
Use LAZY fetching for associations
Avoid hibernate.hbm2ddl.auto=update in production
Use DTOs for complex queries
Enable connection pooling (HikariCP)
Advantages of JPA + Hibernate
Reduces boilerplate JDBC code
Improves productivity and maintainability
Database independence
Powerful caching and performance optimizations
Conclusion
Using JPA with Hibernate provides a robust and standardized ORM solution for Java applications. By writing code against the JPA specification and leveraging Hibernate’s powerful implementation, developers can build scalable, maintainable, and database-independent applications with minimal SQL and maximum flexibility.
Learn Full Stack JAVA Course in Hyderabad
Read More
Connecting Java Applications to MySQL
CRUD Operations in MySQL for Java Developers
Introduction to Relational Databases
Visit Our Quality Thought Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments