Sub topic 3
The Persistence Context and Entity States
Assume core Java, basic SQL, and Spring Boot dependency injection. You should also know that a transaction groups database work into one unit.
The persistence context and entity states
The persistence context is the set of entities currently tracked by an EntityManager. A loaded entity is usually managed, so Hibernate detects changes to it.
| State | Meaning |
|---|---|
| Transient | A new object not known to JPA |
| Managed | Tracked inside the current persistence context |
| Detached | Previously managed, but no longer tracked |
| Removed | Marked for deletion at flush time |
Calling repository.findById inside a transaction returns a managed entity. Calling save on a new entity makes it persistent. After the transaction ends, the entity becomes detached.
Transactions and when changes are flushed
@Transactional defines the boundary of a transaction. Hibernate uses dirty checking, which compares managed entities with their original values. It sends SQL during a flush, commonly just before commit.
Therefore, changing a managed entity does not normally require another save call. The transaction must remain open while the change is made.
Lazy loading, N+1 selects, and fetch strategies
Lazy loading retrieves an association only when code accesses it. This reduces initial work, but accessing a lazy association after the transaction closes can cause LazyInitializationException.
An N+1 query problem occurs when one query loads N books and then one extra author query runs for each book. Use a JPQL join fetch, @EntityGraph, or a carefully designed query to load required data together.
Interface and DTO projections
A projection returns only selected columns instead of complete entities. Interface projections map query aliases to getter names. DTO projections construct a dedicated result class. Use them for read-only screens and reports where entity behavior is unnecessary.
Implementing equals and hashCode for entities
Entity equality is difficult before an identifier exists. Avoid using mutable fields in equals or hashCode, because changing them can corrupt a HashSet. Use a stable, carefully chosen identifier strategy and keep equality consistent throughout an entity’s lifecycle.
Auditing and optimistic locking with `@Version`
Auditing records fields such as creation time, update time, and user. Optimistic locking uses a numeric or timestamp @Version field. Hibernate includes the version in the update condition. If another transaction changed the row first, the update affects no row and an optimistic-lock exception is raised.
Testing repositories with `@DataJpaTest`
@DataJpaTest starts the JPA slice, configures repositories, and usually uses an embedded database. Save test data, execute the repository method, and assert the returned content. This tests mappings and queries without starting the whole application.
Exercise
Why can a lazy association fail after a service method returns?
Show answer
The transaction and persistence context may already be closed, so Hibernate can no longer load the association.