PrepStack › Backend › Spring Data JPA & Hibernate
Spring Data JPA & Hibernate interview cheat sheet
Entities, persistence context, relationships, N+1, @Transactional, locking and caching
Every Java backend interview has a JPA round. Interviewers check that you understand what Hibernate does behind your repository calls: the persistence context, dirty checking, lazy loading, the N+1 problem and how @Transactional really works through proxies. Senior rounds add locking, caching and performance tuning. Read the 15-minute revision first, then use Quiz mode and answer out loud. The SQL snippets show the query shapes Hibernate generates.
15-minute revision
- JPA (Jakarta Persistence) is the spec, Hibernate is the most used implementation, and Spring Data JPA adds repositories on top of JPA. Spring Boot 4 ships Hibernate 7 (Jakarta Persistence 3.2); Boot 3 used Hibernate 6.
- Entity states: transient (new), managed (tracked by the persistence context), detached (context closed), removed (delete scheduled for flush).
- The persistence context is the first-level cache: one Java object per row per
EntityManager.find()checks it before hitting the DB. It is always on and scoped to the transaction in Spring. - Dirty checking: at flush, Hibernate compares each managed entity with its loaded snapshot and issues UPDATEs. You do not need
save()for a managed entity. - Flush sends SQL to the DB; commit makes it permanent. Default
FlushModeType.AUTOflushes before commit and before queries that touch dirty tables. - Spring Data
save()callspersist()if the entity is new (null id or null version), otherwisemerge().merge()returns a new managed copy; always use the returned object. - Default fetch:
@ManyToOne/@OneToOneare EAGER,@OneToMany/@ManyToManyare LAZY. Best practice: make everything LAZY and fetch per use case. - The owning side holds the foreign key. In a bidirectional one-to-many,
@ManyToOneowns it and@OneToMany(mappedBy = ...)is the inverse side. Only the owning side is written to the DB. - orphanRemoval deletes a child that is removed from the parent's collection.
CascadeType.REMOVEonly deletes children when the parent itself is deleted. - N+1: 1 query for N parents plus 1 query per parent for a lazy association. Fix with
JOIN FETCH,@EntityGraph,@BatchSize/default_batch_fetch_size, or DTO projections. LazyInitializationException= touching an uninitialized lazy proxy after the session closed. Fix by fetching what you need inside the transaction, not with EAGER or OSIV.@Transactionalworks through a proxy: self-invocation,privatemethods and calls from the same class skip it. It rolls back onRuntimeException/Erroronly, not checked exceptions (unless configured).- Propagation:
REQUIRED(default, join or create),REQUIRES_NEW(suspend and start a new tx),NESTED(savepoint),MANDATORY,SUPPORTS,NOT_SUPPORTED,NEVER. - Optimistic locking =
@Versioncolumn +UPDATE ... WHERE version = ?; 0 rows updated means a conflict. Pessimistic =SELECT ... FOR UPDATEvia@Lock(PESSIMISTIC_WRITE). - Caches: L1 per persistence context (always), L2 shared per
SessionFactory(opt-in, by id), query cache stores result ids (opt-in, invalidated on any table change). - Set
spring.jpa.open-in-view=falsefor REST APIs, useGenerationType.SEQUENCEwith JDBC batching, read with DTO projections, and use@Transactional(readOnly = true)for queries.
Foundations & mapping
JPA vs Hibernate vs Spring Data JPA
JPA is the specification, Hibernate implements it, and Spring Data JPA generates repositories that call JPA for you.
- JPA / Jakarta Persistence is a specification: annotations (
@Entity,@Id,@OneToMany), theEntityManagerAPI and JPQL. Since 3.0 the package isjakarta.persistence, notjavax.persistence. - Hibernate ORM is a JPA provider (others: EclipseLink). It also has extras outside the spec:
@BatchSize,@DynamicUpdate,@SoftDelete,StatelessSession, Envers. - Spring Data JPA sits on top. You declare an interface like
UserRepository extends JpaRepository<User, Long>and Spring creates the implementation (SimpleJpaRepository) at startup. - Layers: your code → Spring Data repository →
EntityManager(JPA) → HibernateSession→ JDBC → database. Each layer is a leaky abstraction, so you still need to know SQL. - Versions now: Spring Boot 4 uses Hibernate 7 (Jakarta Persistence 3.2). Spring Boot 3 used Hibernate 6. Hibernate 7 removed the old
Session.save/update/saveOrUpdate.
Interview questions
- What is the difference between JPA, Hibernate and Spring Data JPA?
- What is an ORM and what problem does it solve?
- When would you not use JPA?
Entity mapping & ID generation
An entity is a class with @Entity and an @Id. Pick SEQUENCE ids where the DB supports them, because they allow batching.
- Rules for an entity:
@Entity, an@Id, a public or protected no-arg constructor, a top-level class, and notfinal(Hibernate subclasses it for lazy proxies). Records cannot be entities, but they are great as DTOs. - Common column annotations:
@Table,@Column(nullable, length, unique),@Enumerated(EnumType.STRING),@Lob,@Transient(not persisted),@Embedded/@Embeddablefor value objects likeAddress. - Always use
EnumType.STRING. The defaultORDINALstores 0, 1, 2, so inserting a new enum constant in the middle silently corrupts old data. @GeneratedValuestrategies:AUTO(provider picks),IDENTITY(auto-increment column),SEQUENCE(DB sequence),TABLE(a counter table),UUID(JPA 3.1+).IDENTITYforces Hibernate to run the INSERT immediately atpersist()to learn the id, which disables JDBC insert batching.SEQUENCEwithallocationSize(default 50) fetches ids in blocks, so inserts can be batched.- Composite keys use
@EmbeddedId(an@Embeddablekey class) or@IdClass. The key class must implementequals/hashCodeand beSerializable.
Interview questions
- What are the requirements for a JPA entity class?
- IDENTITY vs SEQUENCE: which do you prefer and why?
- Why use
EnumType.STRINGinstead of the default?
Persistence context & entity state
Entity lifecycle states
An entity is transient, managed, detached or removed. Only managed entities are tracked and saved automatically.
- Transient (new): created with
new, not linked to any persistence context, no row yet. Changes are ignored. - Managed (persistent): in the current persistence context, after
persist(),find(), a query, ormerge()'s return value. Changes are saved at flush. - Detached: was managed, but the context closed (transaction ended), or
detach()/clear()was called. It has an id, but changes are not tracked. - Removed:
remove()was called on a managed entity. The DELETE runs at flush. Callingpersist()on it again makes it managed again. - Invalid moves throw:
persist()on a detached entity (Hibernate: “detached entity passed to persist”),remove()on a detached entity (IllegalArgumentException). - Lifecycle callbacks:
@PrePersist,@PostPersist,@PreUpdate,@PostUpdate,@PreRemove,@PostRemove,@PostLoad. Put them on the entity or in an@EntityListenersclass.
Interview questions
- Explain the entity lifecycle states in JPA.
- How does an entity become detached?
- What happens if you call
persist()on a detached entity?
Persistence context & first-level cache
The persistence context is an identity map of managed entities plus their loaded snapshots. It lives as long as the transaction.
- Each
EntityManager(HibernateSession) owns one persistence context: a map of(entity type, id) → managed instance, plus a snapshot of each entity's loaded state. - First-level cache:
find()and lazy loads by id look in the context first. Twofind(User.class, 1L)calls return the same instance and run one SELECT. - Identity guarantee: inside one context there is at most one Java object per row, so
a == bworks for the same id. This gives application-level repeatable reads. - JPQL/Criteria queries always go to the database, but rows that are already managed are returned as the existing instance. Its in-memory state is not overwritten.
- In Spring, the injected
EntityManageris a shared proxy bound to the current transaction. A new transaction means a new, empty context. It is never shared between threads. - The context grows with every loaded entity. In batch jobs, call
flush()andclear()every N rows, or use aStatelessSession, to avoid memory blow-up and slow dirty checks.
Interview questions
- What is the persistence context?
- What is the first-level cache? Can you disable it?
- If I run the same JPQL query twice in one transaction, how many SQL queries run?
Dirty checking & flush modes
At flush Hibernate diffs every managed entity against its snapshot and sends the SQL. Flush is not commit.
- Dirty checking: at flush, each managed entity's current values are compared with the loaded snapshot. Changed entities get an UPDATE. You never need
save()for a managed entity. - Flush = write pending changes to the DB inside the current transaction. Commit = make them permanent. After a flush, a rollback still undoes everything.
- JPA flush modes:
AUTO(default: flush before commit and before a query that could see pending changes) andCOMMIT(flush only at commit). Hibernate addsALWAYSandMANUAL. - Hibernate is write-behind: SQL is queued in an action queue and run at flush in a fixed order: inserts, updates, collection changes, then deletes last.
- By default Hibernate updates all columns (one cached statement per entity).
@DynamicUpdatewrites only changed columns, which helps wide tables and reduces conflicts. - Spring's
@Transactional(readOnly = true)with Hibernate sets the session flush mode toMANUALand loads entities read-only, so no dirty checking happens.
Interview questions
- What is dirty checking in Hibernate?
- What is the difference between flush and commit?
- When does Hibernate flush automatically?
- I updated an entity but no UPDATE ran. Why?
save vs persist vs merge
persist makes the same object managed, merge returns a managed copy, and Spring Data save picks one of them using isNew.
em.persist(e): for new entities. The same instance becomes managed. Returnsvoid. INSERT at flush (or immediately withIDENTITY).em.merge(e): for detached (or new) entities. It loads the managed instance (SELECT if not in context), copies the state onto it, and returns the managed copy. The argument stays detached.- Spring Data
save(e)callspersistifisNew(e), otherwisemerge. By default an entity is new when its non-primitive@Versionis null, or (without a version) when its id is null. - Assigned ids (you set the id yourself) look “not new”, so
save()callsmerge()and runs an extra SELECT before the INSERT. Fix withPersistable<ID>.isNew()or a@Versionfield. saveAndFlush()= save + immediate flush.saveAll()loops oversave().getReferenceById()returns a lazy proxy without a SELECT;findById()returns anOptionaland hits the context or DB.- Hibernate's old
Session.save(),update()andsaveOrUpdate()were deprecated in 6 and removed in Hibernate 7. Usepersistandmerge.
Interview questions
- What is the difference between
persist()andmerge()? - How does Spring Data JPA's
save()decide between insert and update? getReferenceById()vsfindById()?- Why does
save()with a manually assigned id run a SELECT before the INSERT?
Relationships & fetching
Relationships, owning side & mappedBy
The owning side holds the foreign key and is the only side Hibernate reads when writing. mappedBy marks the inverse side.
@ManyToOne+@JoinColumn: the child table has the FK. This is the owning side of a bidirectional one-to-many and the most efficient mapping.@OneToMany(mappedBy = "author"): the inverse side. It is a view of the FK owned by the other entity. Changing only this collection writes nothing to the FK.- Keep both sides in sync with helper methods (
addBooksetsbook.setAuthor(this)and adds to the list). Otherwise the in-memory model is wrong until the next load. - Unidirectional
@OneToManywithoutmappedBymakes Hibernate use a join table (or extra UPDATEs with@JoinColumn). Prefer@ManyToOnealone, or bidirectional. @ManyToManyuses a join table; the side withoutmappedByowns it. Use aSet, not aList. If the link needs extra columns (date, role), map the join table as its own entity with two@ManyToOnes.@OneToOne: the FK lives on the owning side. Prefer@MapsId(shared primary key). The inverse (mappedBy) side of a one-to-one cannot be lazy without bytecode enhancement.
Interview questions
- What is the owning side of a relationship and why does it matter?
- What does
mappedBydo? - How would you model a many-to-many with extra columns like
enrolledAt? - How should you implement
equals/hashCodefor entities?
Cascade types & orphanRemoval
Cascade passes an operation from parent to children. orphanRemoval deletes a child once it leaves the parent's collection.
- Cascade types:
PERSIST,MERGE,REMOVE,REFRESH,DETACH, andALL. They are set on the parent side, usually@OneToManyor@OneToOne. - Use cascades for parent-child aggregates where the child cannot live alone (Order → OrderLine). Do not cascade towards shared entities.
- Never cascade
REMOVEon@ManyToOneor@ManyToMany. Deleting one book could delete its author, and with it the author's other books. orphanRemoval = true: if a child is removed from the collection (or the@OneToOnereference is set to null/replaced), Hibernate deletes its row.CascadeType.REMOVEonly acts when the parent is deleted.orphanRemovalalso covers “child detached from parent” while the parent lives.- With
orphanRemoval, never replace the collection (setBooks(new ArrayList<>())). Hibernate loses track of it and fails. Callclear()andaddAll()instead.
Interview questions
- What is the difference between
CascadeType.REMOVEandorphanRemoval = true? - Which cascade types do you use for a parent-child aggregate?
- Why is cascading REMOVE on
@ManyToManydangerous?
Fetch types, proxies & LazyInitializationException
LAZY loads an association on first access through a proxy. Accessing it after the session closes throws LazyInitializationException.
- Defaults:
@ManyToOneand@OneToOneare EAGER;@OneToManyand@ManyToManyare LAZY. Best practice isfetch = FetchType.LAZYeverywhere. - EAGER is a mapping-level choice you cannot turn off in a query. It loads data you may not need, and for JPQL queries it often causes an extra SELECT per row (N+1).
- Lazy
@ManyToOneis a proxy subclass holding only the id;getId()does not trigger loading. Lazy collections are Hibernate wrappers (PersistentBag,PersistentSet) that load on first use. LazyInitializationException(“could not initialize proxy - no Session”) happens when an uninitialized proxy or collection is accessed after the persistence context closed, typically in the controller or JSON serializer.- Good fixes: fetch what the use case needs inside the transaction with
JOIN FETCH,@EntityGraph, orHibernate.initialize(), or return a DTO projection. - Bad fixes: switching to EAGER, enabling
hibernate.enable_lazy_load_no_trans(a new session and connection per lazy load), or relying on Open Session in View.
Interview questions
- What are the default fetch types in JPA?
- What causes
LazyInitializationExceptionand how do you fix it properly? - Why is
FetchType.EAGERconsidered bad? - How does lazy loading work internally?
The N+1 query problem & fixes
Loading N parents and then touching a lazy association on each one fires 1 + N queries. Fetch the association up front or in batches.
- N+1: one query returns N rows, then accessing a lazy (or EAGER-by-query) association on each row runs one more query per row. 100 orders → 101 queries.
JOIN FETCHin JPQL loads parents and the association in one query. Hibernate 6+ de-duplicates parent rows automatically, soDISTINCTis no longer needed for that.@EntityGraph(attributePaths = ...)on a repository method does the same declaratively.type = FETCHmakes unlisted attributes lazy;LOADkeeps their mapped fetch type.@BatchSize(size = 50)orhibernate.default_batch_fetch_sizeloads lazy associations for many parents at once withWHERE fk IN (...). N+1 becomes 1 + N/50, and it works with pagination.- Limits of
JOIN FETCH: you cannot fetch twoList(bag) collections at once (MultipleBagFetchException), and paginating a collection fetch makes Hibernate paginate in memory (warning HHH90003004). - Detect it early: log SQL in dev (
logging.level.org.hibernate.SQL=debug), enablehibernate.generate_statistics, and assert query counts in integration tests.
Interview questions
- What is the N+1 select problem?
- How do you fix N+1 in Spring Data JPA?
- Why can't you combine JOIN FETCH on a collection with pagination?
- What is
MultipleBagFetchException?
Spring Data repositories
Repository interfaces & derived queries
Extend JpaRepository<T, ID> and Spring generates the implementation; method names like findByEmailAndActiveTrue become queries.
- Hierarchy:
Repository(marker) →CrudRepository/ListCrudRepository→PagingAndSortingRepository/ListPagingAndSortingRepository→JpaRepository(addsflush,saveAndFlush,deleteAllInBatch,getReferenceById, query by example). - Since Spring Data 3,
PagingAndSortingRepositoryno longer extendsCrudRepository, and theList*variants returnListinstead ofIterable. - The runtime implementation is
SimpleJpaRepository. It is@Transactional(readOnly = true)at class level, with read-write transactions on modifying methods likesaveanddelete. - Derived queries are parsed from the method name at startup: prefix (
find,read,get,query,count,exists,delete) +By+ properties with keywords (And,Or,Between,LessThan,Like,Containing,In,IsNull,IgnoreCase,OrderBy,Top10/First). - A typo in a property name fails application startup, which is a nice safety net. Long names (more than 2–3 conditions) are a sign to switch to
@Queryor Specifications. - Return types: entity,
Optional<T>,List<T>,Stream<T>(inside a transaction, close it),Page<T>,Slice<T>, projections, andboolean/longforexists/count.
Interview questions
- What is the difference between
CrudRepositoryandJpaRepository? - How do derived query methods work?
- Who provides the implementation of a repository interface?
@Query, JPQL vs native, projections
Use JPQL for entity queries, native SQL for database-specific features, and projections to read only the columns you need.
- JPQL works on entities and fields (
select u from User u where u.email = :email) and is portable. Hibernate 6+ HQL also supports CTEs, window functions and set operations. - Native queries (
@Query(nativeQuery = true)or@NativeQuery) run SQL as-is: vendor features, hints, complex reports. They bypass entity names and are not portable. - Update and delete queries need
@Modifying(and a transaction). They skip the persistence context, so useclearAutomatically = true(andflushAutomatically = true) to avoid stale managed entities. - Projections: interface-based (getters matching fields; closed ones select only those columns), class/record DTOs (constructor parameters), and dynamic (
<T> List<T> findByX(..., Class<T> type)). - JPQL constructor expressions build DTOs directly:
select new com.app.dto.OrderSummary(o.id, o.total) from Order o. - For dynamic filters (optional search fields) use Specifications (
JpaSpecificationExecutor), Querydsl or the Criteria API, not string concatenation.
Interview questions
- What is the difference between JPQL and native SQL queries?
- Why do update/delete queries need
@Modifying? - What kinds of projections does Spring Data JPA support?
- How do you build a search API with many optional filters?
Pagination & sorting
Pass a Pageable to get one page. Page also runs a count query, Slice does not, and keyset scrolling avoids deep OFFSETs.
PageRequest.of(page, size, Sort.by("createdAt").descending()): page numbers are zero-based. In Spring MVC,?page=0&size=20&sort=name,descbinds to aPageableparameter.Page<T>= content + total elements/pages, so Spring Data runs an extra count query.Slice<T>only knows if a next page exists (it fetches size + 1).List<T>with aPageableruns no count.- For complex
@Querys, give acountQueryso the count stays cheap (no fetch joins, no ORDER BY). - OFFSET pagination gets slower on deep pages: the DB still reads and throws away all skipped rows. Keyset (seek) pagination continues from the last seen key with
WHERE id > :lastId. - Spring Data 3.1+ supports keyset scrolling with
Window<T>andScrollPosition.keyset(). Sorting must be on a unique, indexed key (or include the id as a tiebreaker). - Always sort when paging. Without
ORDER BY, the database may return rows in any order and pages can overlap or skip rows.
Interview questions
- What is the difference between
PageandSlice? - Why is OFFSET pagination slow on deep pages and what is the alternative?
Transactions & concurrency
@Transactional: propagation, isolation, readOnly, rollback
@Transactional wraps a method in a transaction through an AOP proxy. Propagation decides how it joins existing transactions.
- Spring creates a proxy around the bean. On each external call,
TransactionInterceptorasks thePlatformTransactionManager(JpaTransactionManagerfor JPA) to begin, then commits or rolls back when the method ends. - Propagation decides what happens if a transaction already exists. The default
REQUIREDjoins it;REQUIRES_NEWsuspends it and starts an independent one on a new connection. - Isolation (
DEFAULT,READ_UNCOMMITTED,READ_COMMITTED,REPEATABLE_READ,SERIALIZABLE) is applied only when a new transaction starts.DEFAULTuses the DB's level: READ COMMITTED on PostgreSQL/Oracle/SQL Server, REPEATABLE READ on MySQL InnoDB. readOnly = true: with Hibernate, flush mode becomes MANUAL and entities are loaded read-only (no snapshots, no dirty checking). The JDBC connection is marked read-only, which drivers or routing data sources can use for replicas.- Rollback rules: by default only unchecked exceptions (
RuntimeException) andErrorroll back. Checked exceptions commit. UserollbackFor/noRollbackFor, or since Spring 6.2@EnableTransactionManagement(rollbackOn = ALL_EXCEPTIONS). - Put
@Transactionalon service methods (the unit of work), not on controllers. Method-level settings override class-level ones.timeoutis in seconds.
Interview questions
- How does
@Transactionalwork internally? - Explain
REQUIREDvsREQUIRES_NEWvsNESTED. - Does
@Transactionalroll back on checked exceptions? - What does
readOnly = trueactually do?
@Transactional pitfalls: self-invocation & friends
Most @Transactional bugs come from bypassing the proxy, swallowing exceptions, or doing slow work inside the transaction.
- Self-invocation:
this.save()from another method in the same class does not go through the proxy, so its@Transactionalsettings are ignored. - Fixes for self-invocation: move the method to another bean (cleanest), use
TransactionTemplate, inject the bean's own proxy (@Lazyself-reference), or use AspectJ weaving mode. - Visibility:
privatemethods are never intercepted. Since Spring 6.0,protectedand package-private methods work with class-based (CGLIB) proxies.finalmethods cannot be proxied by CGLIB. - Swallowed exceptions: catching an exception inside the method means the interceptor never sees it, so the transaction commits. Rethrow, or call
setRollbackOnly(). UnexpectedRollbackException: an innerREQUIREDmethod threw, marking the shared transaction rollback-only; the outer method caught it and tried to commit.- Long transactions: HTTP calls, file uploads or Kafka sends inside
@Transactionalhold a DB connection and row locks the whole time. Keep transactions short and do I/O outside them.
Interview questions
- Why doesn't
@Transactionalwork when I call the method from the same class? - What is
UnexpectedRollbackExceptionand when does it happen? - Does
@Transactionalwork with@AsyncorCompletableFuture? - Why is calling an external HTTP API inside a transaction a bad idea?
Optimistic (@Version) vs pessimistic locking
Optimistic locking detects conflicts at write time with a version column; pessimistic locking blocks others with SELECT ... FOR UPDATE.
- The problem: two users read the same row, both change it, and the second write silently overwrites the first. This is a lost update.
- Optimistic: add
@Version(Long,Integer,Shortor a timestamp). Every UPDATE addsWHERE version = ?and increments it. If 0 rows match, Hibernate throwsOptimisticLockException(Spring:ObjectOptimisticLockingFailureException). - Optimistic locking takes no DB locks, scales well and works across requests: send the version to the client (or as an ETag) and check it on submit. Handle conflicts with a retry or a “please reload” message.
- Pessimistic:
@Lock(LockModeType.PESSIMISTIC_WRITE)issuesSELECT ... FOR UPDATE, so other writers wait until commit.PESSIMISTIC_READuses a shared lock (FOR SHAREwhere supported). - Pessimistic locks need a transaction, can deadlock (lock rows in a consistent order) and should have a timeout (
jakarta.persistence.lock.timeouthint). Hibernate can also issueNOWAITandSKIP LOCKEDfor job queues. - Other modes:
OPTIMISTIC(check the version at commit even if not modified) andOPTIMISTIC_FORCE_INCREMENT(bump the version of an aggregate root when only its children changed).
Interview questions
- What is optimistic locking and how does JPA implement it?
- When would you choose pessimistic over optimistic locking?
- How do you prevent lost updates when a user edits a form for 10 minutes?
- What happens to
@Versionwith bulk JPQL updates?
Caching, OSIV, inheritance & performance
Second-level cache & query cache
L1 is per persistence context and always on. L2 is shared across sessions and opt-in per entity. The query cache stores result ids.
- First-level (L1): the persistence context. Per
EntityManager/transaction, always enabled, no configuration. - Second-level (L2): per
SessionFactory, shared by all sessions and threads. Opt-in: a provider (JCache with Ehcache 3, Infinispan, Hazelcast) plus@Cacheable(or@org.hibernate.annotations.Cache) on each entity. - L2 stores disassembled entity state (field values by id), not your objects. It serves
find(),getReferenceById()and lazy loads by id. Normal JPQL queries still go to the DB. - Query cache: stores the ids returned by a query for given parameters. On a hit, entities are read from L2. It is invalidated whenever any table in the query changes, so it suits read-mostly data.
- Concurrency strategies:
READ_ONLY(immutable reference data),NONSTRICT_READ_WRITE(rare updates, short staleness OK),READ_WRITE(soft locks, strong consistency),TRANSACTIONAL(JTA providers). - Collections are cached separately (
@Cacheon the collection field) and store only child ids. Cache the child entities too, or you get N+1 from the cache.
Interview questions
- What is the difference between the first-level and second-level cache?
- How does the query cache work and when is it useful?
- Which cache concurrency strategy would you choose?
Open Session in View (OSIV)
OSIV keeps the persistence context open for the whole web request so the view can lazy-load. Spring Boot enables it by default; turn it off for APIs.
- Spring Boot registers
OpenEntityManagerInViewInterceptorby default (spring.jpa.open-in-view=true) and logs a startup warning suggesting you configure it explicitly. - With OSIV, the
EntityManageropens at the start of the request and closes after the response is rendered. Lazy associations work in controllers, templates and JSON serialization. - Cost: the persistence context (and usually a DB connection) lives for the whole request, including rendering and slow clients. That hurts connection pool capacity under load.
- Lazy loads after the service transaction run outside any transaction, one statement at a time (auto-commit). N+1 problems move into the view layer where nobody sees them.
- It blurs layers: the service no longer defines what data a use case needs. With OSIV off, a
LazyInitializationExceptionshows you exactly where a fetch plan is missing. - Recommended:
spring.jpa.open-in-view=false, fetch per use case in services, and return DTOs from controllers.
Interview questions
- What is Open Session in View and why is it considered an anti-pattern?
- Is OSIV enabled by default in Spring Boot?
- After disabling OSIV, the app throws LazyInitializationException everywhere. What do you do?
Inheritance strategies & auditing
Choose SINGLE_TABLE for speed, JOINED for normalization, @MappedSuperclass for shared fields; use Spring Data auditing for created/modified columns.
SINGLE_TABLE(default): all subclasses in one table with a discriminator column (dtype). Fastest polymorphic queries, but subclass columns must be nullable.JOINED: a parent table plus one table per subclass sharing the primary key. Normalized and allows NOT NULL, but every polymorphic query needs joins.TABLE_PER_CLASS: one full table per concrete class. Polymorphic queries becomeUNION ALL, andIDENTITYids cannot be used. Rarely the right choice.@MappedSuperclass: not an entity, just shared mapped fields (id, version, audit columns) copied into each subclass table. No polymorphic queries on the base type.- Spring Data auditing:
@EnableJpaAuditing+@EntityListeners(AuditingEntityListener.class)fills@CreatedDate,@LastModifiedDate,@CreatedBy,@LastModifiedBy. The user comes from anAuditorAware<T>bean. - Alternatives: Hibernate
@CreationTimestamp/@UpdateTimestamp, JPA@PrePersist/@PreUpdatecallbacks, and Hibernate Envers (@Audited) for full history tables.
Interview questions
- Compare the JPA inheritance strategies.
- What is the difference between
@MappedSuperclassand@Inheritance? - How do you add created/updated audit columns automatically?
Performance tuning checklist
Fetch only what you need, batch your writes, keep persistence contexts small, and always look at the generated SQL.
- See the SQL: log
org.hibernate.SQLin dev, enablehibernate.generate_statistics, and test query counts. Most JPA performance bugs are invisible until you look. - Reads: LAZY everywhere, fetch joins or entity graphs per use case,
default_batch_fetch_sizeas a safety net, DTO projections for lists and reports,readOnly = truetransactions. - Writes:
SEQUENCEids,hibernate.jdbc.batch_size(e.g. 50) withorder_inserts/order_updates,flush()+clear()every batch, bulk JPQL or SQL for mass updates. - Big reads: paginate with keyset, or stream with
Stream<T>plus a fetch size, and detach or clear as you go. NeverfindAll()a large table. - Database side: index foreign keys and filter columns (PostgreSQL does not index FKs automatically), size the HikariCP pool to the DB, and keep transactions short.
- Schema:
ddl-auto=validateornonein production with Flyway/Liquibase. Turn onhibernate.query.in_clause_parameter_paddingfor varyingINlists to reuse query plans.
Interview questions
- How do you make bulk inserts fast with Hibernate?
- A list endpoint is slow. How do you investigate?
- Why use DTO projections instead of entities for read-only screens?
- What
ddl-autosetting do you use in production and why?