1. Hibernate and ORM
Hibernate ORM is a Java ORM framework and a JPA provider. JPA is the Jakarta Persistence standard/API; Hibernate is one implementation/provider.
JPA
Standard API and persistence semantics.
Hibernate
ORM implementation with additional provider-specific capabilities.
Modern namespace: Current Jakarta Persistence applications use jakarta.persistence.*. Older applications may still use the legacy javax.persistence.* namespace.
2. Bootstrap and Session
Hibernate Native Bootstrap – Learning Example
StandardServiceRegistry registry =
new StandardServiceRegistryBuilder()
.configure()
.build();
try {
SessionFactory sessionFactory =
new MetadataSources(registry)
.buildMetadata()
.buildSessionFactory();
try (Session session = sessionFactory.openSession()) {
Transaction tx = session.beginTransaction();
Employee employee = new Employee("Srikanth", 90000);
session.persist(employee);
tx.commit();
} finally {
sessionFactory.close();
}
} finally {
StandardServiceRegistryBuilder.destroy(registry);
}
Important Objects
| Object | Purpose |
|---|
| SessionFactory | Heavyweight factory, normally long-lived and shared. |
| Session | Short-lived unit of work / persistence context for native Hibernate APIs. |
| Transaction | Groups database operations into a transaction. |
| Query | Executes HQL/JPQL/native SQL depending on API. |
3. Entity Mapping
Program – Entity
import jakarta.persistence.*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
private BigDecimal salary;
protected Employee() {
// Required by JPA entity construction rules.
}
public Employee(String name, BigDecimal salary) {
this.name = name;
this.salary = salary;
}
// getters and setters
}
CRUD Program
EntityManager em = emf.createEntityManager();
try {
EntityTransaction tx = em.getTransaction();
tx.begin();
Employee e = new Employee("Ravi", new BigDecimal("75000"));
em.persist(e); // Create
Employee found = em.find(Employee.class, e.getId()); // Read
found.setSalary(new BigDecimal("80000")); // Update
em.remove(found); // Delete
tx.commit();
} finally {
em.close();
}
4. Entity Lifecycle
| State | Meaning |
| Transient | New object not associated with a persistence context. |
| Managed / Persistent | Associated with the persistence context; changes can be detected and synchronized. |
| Detached | Previously managed but no longer associated with the current persistence context. |
| Removed | Managed entity scheduled for removal. |
Employee e = new Employee("A", salary); // transient
em.persist(e); // managed
em.detach(e); // detached
em.remove(e); // only valid for managed entity
5. Relationships
Many-to-One / One-to-Many
@Entity
class Order {
@Id @GeneratedValue
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "customer_id")
private Customer customer;
}
@Entity
class Customer {
@Id @GeneratedValue
private Long id;
@OneToMany(mappedBy = "customer")
private List<Order> orders = new ArrayList<>();
}
Many-to-Many
@ManyToMany
@JoinTable(
name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
private Set<Course> courses = new HashSet<>();
Design point: Use cascade and orphanRemoval deliberately. They are lifecycle semantics, not merely performance options.
6. Inheritance Mapping
| Strategy | Idea |
|---|
| SINGLE_TABLE | One table for the hierarchy; discriminator identifies subtype. |
| JOINED | Base and subclass tables joined by primary keys. |
| TABLE_PER_CLASS | Concrete classes have their own tables. |
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "employee_type")
public class Employee {
@Id @GeneratedValue
private Long id;
}
@Entity
@DiscriminatorValue("MANAGER")
public class Manager extends Employee {
private BigDecimal bonus;
}
7. HQL / JPQL
JPQL queries entities and their persistent attributes rather than directly naming database tables and columns. Hibernate's HQL is Hibernate's object-oriented query language and supports Hibernate-specific capabilities beyond the standard.
Program – JPQL
TypedQuery<Employee> query =
entityManager.createQuery(
"select e from Employee e where e.salary > :salary",
Employee.class);
query.setParameter("salary", new BigDecimal("50000"));
List<Employee> employees = query.getResultList();
Pagination
query.setFirstResult(0); // offset
query.setMaxResults(20); // page size
List<Employee> page = query.getResultList();
Fetch Join
select distinct c
from Customer c
left join fetch c.orders
where c.id = :id
8. Fetching and the N+1 Problem
| Approach | Meaning |
|---|
| LAZY | Association/entity data is intended to be loaded when accessed, subject to provider behavior and mapping. |
| EAGER | Provider is expected to make the relationship available eagerly; it can increase query/data load. |
Typical N+1 Problem
List<Customer> customers = query.getResultList();
for (Customer c : customers) {
System.out.println(c.getOrders().size());
}
// 1 query for customers + additional queries for orders
// can become N+1 queries.
Common solution: Fetch the required graph deliberately using a fetch join, entity graph, batch fetching, or another appropriate strategy rather than blindly changing every association to EAGER.
9. Hibernate Caching
| Cache | Scope |
|---|
| First-level cache | Associated with the current persistence context/session; normally always present. |
| Second-level cache | Shared across sessions when configured with a supported cache provider and mappings. |
| Query cache | Optional Hibernate feature for caching query result information; requires deliberate configuration. |
Session session = sessionFactory.openSession();
Employee a = session.find(Employee.class, 1L);
Employee b = session.find(Employee.class, 1L);
// Within the same persistence context/session,
// the managed entity can be served from the first-level cache.
10. Transactions
EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
entityManager.persist(new Employee("A", salary));
entityManager.persist(new Employee("B", salary));
tx.commit();
} catch (RuntimeException ex) {
if (tx.isActive()) {
tx.rollback();
}
throw ex;
}
Flush vs Commit
- Flush: Synchronizes pending persistence-context changes with the database; it is not the same thing as committing the transaction.
- Commit: Completes the transaction and makes its changes durable according to database transaction semantics.
11. Hibernate + Spring Data JPA
In Spring Boot applications, Hibernate is commonly used as the JPA provider while application code uses Jakarta Persistence APIs and Spring Data repositories.
Repository Program
public interface EmployeeRepository
extends JpaRepository<Employee, Long> {
List<Employee> findByNameContainingIgnoreCase(String name);
}
Service + Pagination
@Service
public class EmployeeService {
private final EmployeeRepository repository;
public EmployeeService(EmployeeRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public Page<Employee> search(String name, int page, int size) {
Pageable pageable =
PageRequest.of(page, size, Sort.by("name").ascending());
return repository.findByNameContainingIgnoreCase(
name, pageable);
}
}
Modern repository hierarchy note: Current Spring Data JPA exposes JpaRepository through the newer list-oriented CRUD/paging interfaces as well as the traditional repository hierarchy. Do not memorize an old simplified inheritance diagram as if it were the current API definition.
12. Hibernate / JPA Interview Revision
| Question | Answer |
| JPA vs Hibernate? | JPA/Jakarta Persistence is a standard; Hibernate is an implementation/provider. |
| SessionFactory vs Session? | SessionFactory is heavyweight and long-lived; Session is a unit of work and persistence context. |
| EntityManager? | Jakarta Persistence API for interacting with the persistence context. |
| Transient vs managed? | Transient is not associated with a persistence context; managed is associated with one. |
| What is N+1? | One query loads parents and additional queries load related data repeatedly. |
| JPQL vs SQL? | JPQL operates on entities and persistent attributes; SQL operates on database tables/columns. |
| First-level cache? | Persistence-context/session-scoped cache. |
| Second-level cache? | Optional shared cache across persistence contexts/sessions. |
| persist vs merge? | persist makes a new entity managed; merge copies state into a managed instance and returns that managed instance. |
| find vs getReference? | find returns the entity or null; getReference may return a lazy reference and defer database access. |