JPA and Hibernate: Entities and the Persistence Context
JPA is the Java persistence specification and Hibernate is its most used implementation. Interviewers ask about the entity lifecycle states, the persistence context (first-level cache), dirty checking, and save vs merge.
What you will learn
- Map an entity with ids and columns
- Name the four entity states
- Explain the persistence context and dirty checking
- Know flush and when SQL actually runs
Key concepts
Entity states
Transient (new, not tracked), Managed (tracked by the persistence context), Detached (was managed, context closed), Removed (scheduled for delete).
Persistence context
The set of managed entities in one EntityManager, usually one per transaction. It is the first-level cache: loading the same id twice returns the same object and runs one query.
Dirty checking
At flush, Hibernate compares managed entities with their loaded snapshot and issues UPDATEs for changed ones. You do not need to call save() on a managed entity.
Flush
Sends pending SQL to the database, at commit, before queries that may be affected, or when you call flush(). The transaction can still roll back after a flush.
Step by step
An entity
@Entity
@Table(name = "orders", indexes = @Index(columnList = "user_id, created_at"))
public class Order {
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private OrderStatus status;
@Column(precision = 12, scale = 2)
private BigDecimal total;
@Version
private int version; // optimistic locking
protected Order() {} // JPA needs a no-arg constructor
}Dirty checking in practice
@Transactional
public void markPaid(Long id) {
Order o = orderRepository.findById(id).orElseThrow();
o.setStatus(OrderStatus.PAID); // no save() needed: UPDATE runs at commit
}Examples
persist vs merge
em.persist(newOrder); // transient → managed (same object)
Order managed = em.merge(dto); // copies state of a detached object onto a managed copy and returns it
// Spring Data save(): persist if the entity is new (id null or version null), otherwise mergePractise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Load the same entity twice in one transaction and count the queries with SQL logging on.
- Explain why EnumType.ORDINAL is dangerous.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
JPA vs Hibernate vs Spring Data JPA?
JPA (Jakarta Persistence) is the specification and annotations. Hibernate is an implementation that does the ORM work. Spring Data JPA is a layer on top that generates repository implementations and query methods for you.
What is the second-level cache?
A cache shared across sessions (Ehcache, Caffeine via JCache, Redis) for rarely changing entities. The first-level cache is per persistence context and always on; the second-level cache is optional and must be configured per entity.
Why GenerationType.SEQUENCE over IDENTITY?
With IDENTITY the database assigns the id during INSERT, so Hibernate must insert immediately and cannot batch inserts. SEQUENCE lets Hibernate fetch ids ahead (with pooled optimisers) and batch.
Summary
Entities move between transient, managed, detached and removed; the persistence context caches them per transaction and dirty checking writes changes at flush, so managed entities need no explicit save.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus