Section 16 · 30 questions

Hibernate JPA

30 interview questions and answers in the Hibernate JPA section.

English Hibernate JPA Source Markdown
Language versions: English Russian Ukrainian

Questions in this section

  1. What is the N+1 Problem and How to Solve It
  2. What is the Difference Between Lazy and Eager Loading
  3. When to Use Lazy vs Eager Loading
  4. What is LazyInitializationException and How to Avoid It
  5. What Fetch Strategies Exist in Hibernate
  6. What Does the @BatchSize Annotation Do
  7. Describe the Entity Lifecycle in Hibernate
  8. What Are the Transient, Persistent, Detached, Removed States
  9. What is the First-Level Cache in Hibernate
  10. What is the Second-Level Cache and When to Use It
  11. How to Configure the Second-Level Cache
  12. What is Dirty Checking in Hibernate
  13. How Does the Flush Mechanism Work in Hibernate
  14. What is the Difference Between persist() and merge()
  15. What Does the refresh() Method Do
  16. What is EntityManager and How Does It Differ from Session
  17. How to Implement Optimistic Locking in JPA
  18. How to Implement Pessimistic Locking in JPA
  19. What is @Version and Why is It Needed
  20. How Do Cascade Operations Work
  21. What Cascade Types Exist
  22. What is Orphan Removal
  23. How to Properly Use @OneToMany and @ManyToOne
  24. What Are the Peculiarities of Bidirectional Relationships
  25. How to Avoid Infinite Recursion When Serializing Entities
  26. What is JPQL and How Does It Differ from SQL
  27. What is Criteria API and When to Use It
  28. How to Use JOIN FETCH to Solve the N+1 Problem
  29. What is Projection in JPA
  30. What Inheritance Types Does JPA Support

Study navigator

30 questions for Middle Java Developer interview preparation.


All Questions

# Question Difficulty
1 What is the N+1 problem and how to solve it 3 stars
2 What is the difference between Lazy and Eager loading 2 stars
3 When to use Lazy vs Eager loading 2 stars
4 What is LazyInitializationException and how to avoid it 2 stars
5 What fetch strategies exist in Hibernate 3 stars
6 What does the @BatchSize annotation do 2 stars
7 Describe the Entity lifecycle in Hibernate 3 stars
8 What are the transient, persistent, detached, removed states 2 stars
9 What is the first-level cache in Hibernate 2 stars
10 What is the second-level cache and when to use it 3 stars
11 How to configure the second-level cache 3 stars
12 What is dirty checking in Hibernate 3 stars
13 How does the flush mechanism work in Hibernate 3 stars
14 What is the difference between persist() and merge() 2 stars
15 What does the refresh() method do 2 stars
16 What is EntityManager and how does it differ from Session 2 stars
17 How to implement optimistic locking in JPA 2 stars
18 How to implement pessimistic locking in JPA 3 stars
19 What is @Version and why is it needed 2 stars
20 How do cascade operations work 2 stars
21 What Cascade types exist 2 stars
22 What is orphan removal 2 stars
23 How to properly use @OneToMany and @ManyToOne 3 stars
24 What are the peculiarities of bidirectional relationships 3 stars
25 How to avoid infinite recursion when serializing Entities 2 stars
26 What is JPQL and how does it differ from SQL 2 stars
27 What is Criteria API and when to use it 3 stars
28 How to use JOIN FETCH to solve the N+1 problem 3 stars
29 What is projection in JPA 2 stars
30 What inheritance types does JPA support 3 stars

Topic Dependency Map

                    ┌──────────────────────────────────────────┐
                    │   FETCH AND N+1 (1-6)                    │
                    │   1. N+1 Problem                         │
                    │   2. Lazy vs Eager                       │
                    │   3. When to use which                   │
                    │   4. LazyInitializationException         │
                    │   5. Fetch Strategies                    │
                    │   6. @BatchSize                          │
                    └──────────────────┬───────────────────────┘
                                       │
            ┌──────────────────────────┼──────────────────────────┐
            ▼                          ▼                          ▼
    ┌───────────────┐        ┌───────────────┐        ┌────────────────────┐
    │ ENTITY         │        │ CACHING       │        │ LOCKING            │
    │ LIFECYCLE      │        │ (9-13)        │        │ (17-19)            │
    │ (7-8, 12-16)   │        │ 9. L1 cache   │        │ 17. Optimistic     │
    │ 7. Lifecycle   │        │ 10. L2 cache  │        │ 18. Pessimistic    │
    │ 8. States      │        │ 11. L2 config │        │ 19. @Version       │
    │ 12. Dirty chk  │        │ 12. Dirty chk │        │                    │
    │ 13. Flush      │        │ 13. Flush     │        │                    │
    │ 14. persist/   │        │               │        │                    │
    │     merge      │        │               │        │                    │
    │ 15. refresh    │        │               │        │                    │
    │ 16. EM vs Sess │        │               │        │                    │
    └───────┬───────┘        └───────┬───────┘        └────────┬───────────┘
            │                        │                        │
            └────────────────────────┼────────────────────────┘
                                     ▼
                    ┌──────────────────────────────────────────┐
                    │   RELATIONSHIPS (20-25)                  │
                    │   20. Cascade overview                   │
                    │   21. Cascade types                      │
                    │   22. Orphan removal                     │
                    │   23. @OneToMany/@ManyToOne              │
                    │   24. Bidirectional                      │
                    │   25. Serialization recursion            │
                    └──────────────────────────────────────────┘
                                     │
            ┌────────────────────────┼────────────────────────┐
            ▼                        ▼                        ▼
    ┌───────────────┐        ┌───────────────┐        ┌────────────────────┐
    │ QUERY LANG     │        │ N+1 SOLUTIONS  │        │ INHERITANCE        │
    │ (26-27)        │        │ (28-29)        │        │ (30)               │
    │ 26. JPQL vs    │        │ 28. JOIN FETCH │        │ 30. Inheritance    │
    │    SQL         │        │ 29. Projection │        │    types           │
    │ 27. Criteria   │        │                │        │                    │
    │    API         │        │                │        │                    │
    └───────────────┘        └───────────────┘        └────────────────────┘

Junior Level (weeks 1-2)

Step Topic Files Goal
1 Entity states Q7, Q8 Transient, Persistent, Detached, Removed
2 Lazy vs Eager Q2, Q3 When to use which
3 persist vs merge Q14 Which method for which state
4 Cascade basics Q20, Q21 What is cascade, what types
5 JPQL vs SQL Q26 Differences, when to use which

Middle Level (weeks 3-4)

Step Topic Files Goal
1 N+1 problem Q1, Q28 Why it occurs, JOIN FETCH solution
2 LazyInitializationException Q4 Why it occurs, 3 solutions
3 Dirty checking Q12, Q13 How it works, when flush
4 L1 cache Q9 Identity guarantee, snapshot
5 @OneToMany/@ManyToOne Q23, Q24 mappedBy, owner/inverse, helper methods
6 Optimistic locking Q17, Q19 @Version, OptimisticLockException
7 Projection Q29 Why, interface-based, class-based

Senior Level (weeks 5-6)

Step Topic Files Goal
1 L2 cache Q10, Q11 Concurrency strategies, clustering, invalidation
2 Pessimistic locking Q18 PESSIMISTIC_READ/WRITE/NONE, NOWAIT, SKIP LOCKED
3 Fetch strategies deep Q5, Q6 FetchMode vs FetchType, SUBSELECT vs BATCH
4 EntityManager vs Session Q16 Internal implementation, Jakarta vs javax
5 Circular cascade Q20, Q22 Cycle detection, orphanRemoval vs REMOVE
6 Criteria API Q27 Type-safe, Metamodel, dynamic queries
7 Inheritance Q30 SINGLE_TABLE vs JOINED vs TABLE_PER_CLASS trade-offs
8 Serialization Q25 Jackson annotations, LazyInitializationException in REST

Key Topic Connections

Topic: Fetch and N+1

Q2 (Lazy vs Eager) -> Q3 (When to use) -> Q4 (LazyInitException)
     ↓
Q5 (Fetch strategies) -> Q6 (@BatchSize) -> Q1 (N+1) -> Q28 (JOIN FETCH)

Key connections:

  • Q2 <-> Q5: FetchType (when) vs FetchMode (how)
  • Q4 <-> Q28: JOIN FETCH prevents LazyInitializationException
  • Q5 <-> Q6: @BatchSize - separate mechanism from FetchMode
  • Q1 <-> Q29: Projection also solves N+1 (loads only needed columns)

Topic: Entity Lifecycle

Q7 (Lifecycle) -> Q8 (States) -> Q14 (persist/merge)
     ↓                ↓
Q12 (Dirty check) -> Q13 (Flush) -> Q15 (refresh)
     ↓
Q16 (EntityManager vs Session)

Key connections:

  • Q8 <-> Q14: persist() for transient, merge() for detached
  • Q12 <-> Q13: Dirty checking triggers flush at commit/before query
  • Q15 <-> Q8: refresh() brings detached back to persistent

Topic: Caching

Q9 (L1 cache) -> Q10 (L2 cache) -> Q11 (L2 config)

Key connections:

  • Q9 <-> Q12: L1 cache stores snapshot for dirty checking
  • Q10 <-> Q11: Provider configuration, clustering, invalidation

Topic: Relationships

Q20 (Cascade) -> Q21 (Cascade types) -> Q22 (Orphan removal)
     ↓
Q23 (@OneToMany/@ManyToOne) -> Q24 (Bidirectional) -> Q25 (Serialization)

Key connections:

  • Q21 <-> Q22: CascadeType.REMOVE vs orphanRemoval
  • Q23 <-> Q24: Bidirectional requires synchronizing both sides
  • Q24 <-> Q25: Bidirectional -> infinite recursion during serialization
  • Q25 <-> Q4: LazyInitializationException when serializing LAZY fields

Topic: Query and Inheritance

Q26 (JPQL) -> Q27 (Criteria API) -> Q28 (JOIN FETCH) -> Q29 (Projection)
     ↓
Q30 (Inheritance)

Key connections:

  • Q26 <-> Q27: JPQL - string-based, Criteria - type-safe
  • Q28 <-> Q1: JOIN FETCH - main N+1 solution
  • Q29 <-> Q26: Projection in JPQL via constructor expression
  • Q30 <-> Q26: Polymorphic queries depend on inheritance strategy

Cheat Sheet: What to Know for Each Level

Junior

  • Entity states: transient (new), persistent (managed), detached (session closed), removed
  • Lazy = load on access, Eager = load immediately. LAZY by default for collections
  • persist() = INSERT for transient, merge() = SELECT+UPDATE for detached
  • Cascade = automatic propagation of operations to related entities
  • JPQL works with entities, SQL - with tables

Middle

  • N+1: 1 query for parent + N for children. Solution: JOIN FETCH, @BatchSize, EntityGraph
  • Dirty checking: Hibernate stores snapshot, at flush compares -> UPDATE if changed
  • L1 cache: EntityManager-level, identity guarantee, snapshot for dirty checking
  • @Version: optimistic locking, version=0 at INSERT, +1 at each UPDATE
  • orphanRemoval: removes child when removed from collection, CascadeType.REMOVE - only when parent is removed
  • Bidirectional: mappedBy on inverse side, helper methods for synchronization

Senior

  • L2 cache: EntityManagerFactory-level, clustering (Hazelcast, Infinispan), eventual consistency
  • Pessimistic locking: PESSIMISTIC_READ (shared), PESSIMISTIC_WRITE (exclusive), NOWAIT, SKIP LOCKED
  • FetchMode JOIN ignores LAZY in Hibernate 5.x. SUBSELECT only if parents loaded in one query
  • Flush order: INSERT -> UPDATE -> DELETE (critical for FK constraints)
  • Cartesian product with multiple JOIN FETCH - Hibernate 6 doesn’t fully resolve
  • @MappedSuperclass != @Entity: no table, cannot query, polymorphic queries don’t work
  • Jackson @JsonManagedReference/@JsonBackReference - not JPA, serializer-specific

File Format

Each file contains:

  • Junior Level - basic understanding, simple analogies, examples
  • Middle Level - internals, common mistakes, practical examples
  • Senior Level - deep dive, edge cases, production experience, monitoring
  • Interview Cheat Sheet - key points, frequent questions, red flags, related topics