Hibernate Basics
Hibernate is Spring Boot's default JPA provider.
Introduction
Hibernate is Spring Boot's default JPA provider. It maps Jakarta entities to rows, tracks dirty state, and manages a per-transaction persistence context. Most mysterious Orders bugs — duplicate updates, lazy failures, N+1 selects — are Hibernate lifecycle misunderstandings.
Inside a transaction, loaded Order instances are managed. Change a field; on flush/commit Hibernate issues UPDATE without an explicit save (though Spring Data save still flushes clearly). The first-level cache means the same id returns the same instance within the persistence context.
Lazy associations load only when touched — and only while the session is open. With open-in-view: false, touching order.getItems() after the service returns throws. Fetch what you need with join fetch or entity graphs inside the transactional method.
Learn the mental model once; every later JPQL and relationship lesson builds on it.
Purpose of this lesson
Explain Hibernate's persistence context, dirty checking, lazy loading, and first-level cache for Orders entities on Boot 3.
Understanding the topic
Hibernate is a unit-of-work engine, not just an SQL generator.
- Persistence context: managed entities for the current transaction.
- Dirty checking: snapshot compare → UPDATE on flush.
- Lazy loading: proxies load on access; need an open session.
- L1 cache: same id → same instance inside one context.
- Flush: synchronizes SQL before query/commit as needed.
Step-by-step explanation
- Disable
spring.jpa.open-in-viewin Orders config. - Load an order inside
@Transactional, mutate status, commit — observe UPDATE without extra repository calls. - Attempt to access a lazy collection after the transaction ends; note the failure.
- Fix with
join fetchor an@EntityGraphinside the service method.
Informative example
Dirty checking + lazy boundary for Orders.
@Servicepublic class OrderService {private final OrderRepository orders;public OrderService(OrderRepository orders) { this.orders = orders; }@Transactionalpublic void markPaid(long id) {Order order = orders.findById(id).orElseThrow(() -> new OrderNotFoundException(id));order.setStatus(OrderStatus.PAID); // dirty → UPDATE on commit}@Transactional(readOnly = true)public OrderDetailView detail(long id) {Order order = orders.findWithItems(id); // join fetch inside reporeturn OrderDetailView.from(order);}}// application.ymlspring.jpa.open-in-view: false
Output
update orders set status='PAID', ... where id=42 -- after TX: LazyInitializationException if items touched without fetch
Real-world use
Support agents open order detail with line items. If Hibernate lazy-loads each item after the transaction, JSON serialization fails or N+1 queries appear. TechLearningPRO fetches items in one query inside the service and maps to a DTO before returning.
Security implications
The persistence context holds sensitive order rows in memory.
- Do not keep long-running transactions that pin large graphs.
- Never serialize managed entities directly to HTTP clients.
- Clear or close contexts promptly so pooled connections return.
Best practices
- Default associations to
FetchType.LAZY. - Use
readOnly = trueon pure query service methods. - Enable SQL logging in dev (
spring.jpa.show-sqlor p6spy) to see real statements.
Common mistakes
- Relying on open-in-view to 'make lazy work' in controllers.
- Calling
savein a loop without understanding flush/batching. - Expecting lazy collections to work in async threads detached from the context.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat is the persistence context?+
Answer
2IntermediateQuestionWhy can changing a field without save still UPDATE?+
Answer
3IntermediateQuestionWhat causes LazyInitializationException in Boot APIs?+
Answer
Hands-on exercise
Lab. With open-in-view false, write markPaid as above and assert one UPDATE. Then write a failing test that accesses items outside the TX, and a passing test that uses join fetch.
Summary
Hibernate's unit of work explains most JPA surprises. Next: map the Orders table with Jakarta entity annotations.