Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 28

    Hibernate Basics

    Hibernate is Spring Boot's default JPA provider.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Disable spring.jpa.open-in-view in Orders config.
    2. Load an order inside @Transactional, mutate status, commit — observe UPDATE without extra repository calls.
    3. Attempt to access a lazy collection after the transaction ends; note the failure.
    4. Fix with join fetch or an @EntityGraph inside the service method.

    Informative example

    Dirty checking + lazy boundary for Orders.

    java
    @Service
    public class OrderService {
    private final OrderRepository orders;
    public OrderService(OrderRepository orders) { this.orders = orders; }
    @Transactional
    public 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 repo
    return OrderDetailView.from(order);
    }
    }
    // application.yml
    spring.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 = true on pure query service methods.
    • Enable SQL logging in dev (spring.jpa.show-sql or p6spy) to see real statements.

    Common mistakes

    • Relying on open-in-view to 'make lazy work' in controllers.
    • Calling save in 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.

    3 questions
    1BeginnerQuestionWhat is the persistence context?+

    Answer

    Hibernate's first-level cache / unit of work for managed entities within a transaction (or extended session).
    2IntermediateQuestionWhy can changing a field without save still UPDATE?+

    Answer

    Dirty checking compares the entity snapshot and flushes changes on commit.
    3IntermediateQuestionWhat causes LazyInitializationException in Boot APIs?+

    Answer

    Accessing a lazy association after the persistence context closes — common when open-in-view is false and fetch was incomplete.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.