Day 09 — Persistence Context, EntityManager & Lifecycle Events¶
Daily Time Investment: 2.5 hours | Week: 2 | Phase: 3
Daily Schedule¶
| Segment | Duration | Activity |
|---|---|---|
| Core Theory | 45 min | 4 entity states, First-Level Cache, dirty checking, flush()/refresh()/merge(), lifecycle callbacks |
| Book Reading | 30 min | Pro Persistence Ch6 (Entity Manager) |
| Hands-On Lab | 75 min | AuditListener via @EntityListeners; prove L1 identity map and auto dirty checking |
Files in This Day¶
-
Pro Persistence Ch6 — EntityManager & Persistence Context
Transaction-scoped vs extended persistence context,
persist(),merge(),remove(),find()vsgetReference(),flush(),refresh(),clear(),detach(), First-Level Cache identity map, cascading operations, web architectural patterns. -
Lab Guide — Persistence Context & Lifecycle
Prove entity state transitions, L1 identity map (same Java reference for repeated
find()), auto dirty checking (UPDATE without explicitmerge()),AuditListenerlogging all@PrePersist/@PostUpdateevents,@PostLoadcomputing transient fields.
Prerequisites to Continue¶
New concepts not seen in Phase 1 or Phase 2
- Transaction-Scoped vs Extended persistence context — transaction-scoped (default) lives only within a JTA transaction; extended lives across multiple transactions (tied to
@StatefulEJBs) - First-Level Cache (Identity Map) — JPA guarantees that within one persistence context,
em.find(T.class, id)for the sameidalways returns the exact same Java object instance (ref1 == ref2) — no second SQL query - Automatic Dirty Checking — Hibernate snapshots entity state at load time; at
flush()/ commit, it compares current state to snapshot and issuesUPDATEautomatically — no explicit save call needed em.merge(detached)— does NOT make the passed argument managed; it copies state into an existing (or new) managed entity and returns the managed copy — always use the return valueem.getReference()— returns a Hibernate proxy without hitting the database; use only for foreign-key associations; throwsEntityNotFoundExceptionlazily if entity doesn't exist@EntityListeners— an external auditing class; method signature must bevoid onEvent(EntityType entity)— different from in-entity callbacks which take no parameters