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

  1. 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.
  2. Entity states: transient (new), managed (tracked by the persistence context), detached (context closed), removed (delete scheduled for flush).
  3. 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.
  4. 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.
  5. Flush sends SQL to the DB; commit makes it permanent. Default FlushModeType.AUTO flushes before commit and before queries that touch dirty tables.
  6. Spring Data save() calls persist() if the entity is new (null id or null version), otherwise merge(). merge() returns a new managed copy; always use the returned object.
  7. Default fetch: @ManyToOne/@OneToOne are EAGER, @OneToMany/@ManyToMany are LAZY. Best practice: make everything LAZY and fetch per use case.
  8. The owning side holds the foreign key. In a bidirectional one-to-many, @ManyToOne owns it and @OneToMany(mappedBy = ...) is the inverse side. Only the owning side is written to the DB.
  9. orphanRemoval deletes a child that is removed from the parent's collection. CascadeType.REMOVE only deletes children when the parent itself is deleted.
  10. 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.
  11. LazyInitializationException = touching an uninitialized lazy proxy after the session closed. Fix by fetching what you need inside the transaction, not with EAGER or OSIV.
  12. @Transactional works through a proxy: self-invocation, private methods and calls from the same class skip it. It rolls back on RuntimeException/Error only, not checked exceptions (unless configured).
  13. Propagation: REQUIRED (default, join or create), REQUIRES_NEW (suspend and start a new tx), NESTED (savepoint), MANDATORY, SUPPORTS, NOT_SUPPORTED, NEVER.
  14. Optimistic locking = @Version column + UPDATE ... WHERE version = ?; 0 rows updated means a conflict. Pessimistic = SELECT ... FOR UPDATE via @Lock(PESSIMISTIC_WRITE).
  15. 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).
  16. Set spring.jpa.open-in-view=false for REST APIs, use GenerationType.SEQUENCE with 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), the EntityManager API and JPQL. Since 3.0 the package is jakarta.persistence, not javax.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) → Hibernate Session → 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 not final (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/@Embeddable for value objects like Address.
  • Always use EnumType.STRING. The default ORDINAL stores 0, 1, 2, so inserting a new enum constant in the middle silently corrupts old data.
  • @GeneratedValue strategies: AUTO (provider picks), IDENTITY (auto-increment column), SEQUENCE (DB sequence), TABLE (a counter table), UUID (JPA 3.1+).
  • IDENTITY forces Hibernate to run the INSERT immediately at persist() to learn the id, which disables JDBC insert batching. SEQUENCE with allocationSize (default 50) fetches ids in blocks, so inserts can be batched.
  • Composite keys use @EmbeddedId (an @Embeddable key class) or @IdClass. The key class must implement equals/hashCode and be Serializable.

Interview questions

  • What are the requirements for a JPA entity class?
  • IDENTITY vs SEQUENCE: which do you prefer and why?
  • Why use EnumType.STRING instead 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, or merge()'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. Calling persist() 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 @EntityListeners class.

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 (Hibernate Session) 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. Two find(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 == b works 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 EntityManager is 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() and clear() every N rows, or use a StatelessSession, 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) and COMMIT (flush only at commit). Hibernate adds ALWAYS and MANUAL.
  • 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). @DynamicUpdate writes only changed columns, which helps wide tables and reduces conflicts.
  • Spring's @Transactional(readOnly = true) with Hibernate sets the session flush mode to MANUAL and 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. Returns void. INSERT at flush (or immediately with IDENTITY).
  • 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) calls persist if isNew(e), otherwise merge. By default an entity is new when its non-primitive @Version is null, or (without a version) when its id is null.
  • Assigned ids (you set the id yourself) look “not new”, so save() calls merge() and runs an extra SELECT before the INSERT. Fix with Persistable<ID>.isNew() or a @Version field.
  • saveAndFlush() = save + immediate flush. saveAll() loops over save(). getReferenceById() returns a lazy proxy without a SELECT; findById() returns an Optional and hits the context or DB.
  • Hibernate's old Session.save(), update() and saveOrUpdate() were deprecated in 6 and removed in Hibernate 7. Use persist and merge.

Interview questions

  • What is the difference between persist() and merge()?
  • How does Spring Data JPA's save() decide between insert and update?
  • getReferenceById() vs findById()?
  • 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 (addBook sets book.setAuthor(this) and adds to the list). Otherwise the in-memory model is wrong until the next load.
  • Unidirectional @OneToMany without mappedBy makes Hibernate use a join table (or extra UPDATEs with @JoinColumn). Prefer @ManyToOne alone, or bidirectional.
  • @ManyToMany uses a join table; the side without mappedBy owns it. Use a Set, not a List. 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 mappedBy do?
  • How would you model a many-to-many with extra columns like enrolledAt?
  • How should you implement equals/hashCode for 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, and ALL. They are set on the parent side, usually @OneToMany or @OneToOne.
  • Use cascades for parent-child aggregates where the child cannot live alone (Order → OrderLine). Do not cascade towards shared entities.
  • Never cascade REMOVE on @ManyToOne or @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 @OneToOne reference is set to null/replaced), Hibernate deletes its row.
  • CascadeType.REMOVE only acts when the parent is deleted. orphanRemoval also 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. Call clear() and addAll() instead.

Interview questions

  • What is the difference between CascadeType.REMOVE and orphanRemoval = true?
  • Which cascade types do you use for a parent-child aggregate?
  • Why is cascading REMOVE on @ManyToMany dangerous?

Fetch types, proxies & LazyInitializationException

LAZY loads an association on first access through a proxy. Accessing it after the session closes throws LazyInitializationException.

  • Defaults: @ManyToOne and @OneToOne are EAGER; @OneToMany and @ManyToMany are LAZY. Best practice is fetch = FetchType.LAZY everywhere.
  • 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 @ManyToOne is 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, or Hibernate.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 LazyInitializationException and how do you fix it properly?
  • Why is FetchType.EAGER considered 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 FETCH in JPQL loads parents and the association in one query. Hibernate 6+ de-duplicates parent rows automatically, so DISTINCT is no longer needed for that.
  • @EntityGraph(attributePaths = ...) on a repository method does the same declaratively. type = FETCH makes unlisted attributes lazy; LOAD keeps their mapped fetch type.
  • @BatchSize(size = 50) or hibernate.default_batch_fetch_size loads lazy associations for many parents at once with WHERE fk IN (...). N+1 becomes 1 + N/50, and it works with pagination.
  • Limits of JOIN FETCH: you cannot fetch two List (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), enable hibernate.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 (adds flush, saveAndFlush, deleteAllInBatch, getReferenceById, query by example).
  • Since Spring Data 3, PagingAndSortingRepository no longer extends CrudRepository, and the List* variants return List instead of Iterable.
  • The runtime implementation is SimpleJpaRepository. It is @Transactional(readOnly = true) at class level, with read-write transactions on modifying methods like save and delete.
  • 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 @Query or Specifications.
  • Return types: entity, Optional<T>, List<T>, Stream<T> (inside a transaction, close it), Page<T>, Slice<T>, projections, and boolean/long for exists/count.

Interview questions

  • What is the difference between CrudRepository and JpaRepository?
  • 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 use clearAutomatically = true (and flushAutomatically = 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,desc binds to a Pageable parameter.
  • 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 a Pageable runs no count.
  • For complex @Querys, give a countQuery so 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> and ScrollPosition.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 Page and Slice?
  • 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, TransactionInterceptor asks the PlatformTransactionManager (JpaTransactionManager for JPA) to begin, then commits or rolls back when the method ends.
  • Propagation decides what happens if a transaction already exists. The default REQUIRED joins it; REQUIRES_NEW suspends 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. DEFAULT uses 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) and Error roll back. Checked exceptions commit. Use rollbackFor/noRollbackFor, or since Spring 6.2 @EnableTransactionManagement(rollbackOn = ALL_EXCEPTIONS).
  • Put @Transactional on service methods (the unit of work), not on controllers. Method-level settings override class-level ones. timeout is in seconds.

Interview questions

  • How does @Transactional work internally?
  • Explain REQUIRED vs REQUIRES_NEW vs NESTED.
  • Does @Transactional roll back on checked exceptions?
  • What does readOnly = true actually 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 @Transactional settings are ignored.
  • Fixes for self-invocation: move the method to another bean (cleanest), use TransactionTemplate, inject the bean's own proxy (@Lazy self-reference), or use AspectJ weaving mode.
  • Visibility: private methods are never intercepted. Since Spring 6.0, protected and package-private methods work with class-based (CGLIB) proxies. final methods 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 inner REQUIRED method 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 @Transactional hold a DB connection and row locks the whole time. Keep transactions short and do I/O outside them.

Interview questions

  • Why doesn't @Transactional work when I call the method from the same class?
  • What is UnexpectedRollbackException and when does it happen?
  • Does @Transactional work with @Async or CompletableFuture?
  • 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, Short or a timestamp). Every UPDATE adds WHERE version = ? and increments it. If 0 rows match, Hibernate throws OptimisticLockException (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) issues SELECT ... FOR UPDATE, so other writers wait until commit. PESSIMISTIC_READ uses a shared lock (FOR SHARE where supported).
  • Pessimistic locks need a transaction, can deadlock (lock rows in a consistent order) and should have a timeout (jakarta.persistence.lock.timeout hint). Hibernate can also issue NOWAIT and SKIP LOCKED for job queues.
  • Other modes: OPTIMISTIC (check the version at commit even if not modified) and OPTIMISTIC_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 @Version with 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 (@Cache on 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 OpenEntityManagerInViewInterceptor by default (spring.jpa.open-in-view=true) and logs a startup warning suggesting you configure it explicitly.
  • With OSIV, the EntityManager opens 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 LazyInitializationException shows 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 become UNION ALL, and IDENTITY ids 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 an AuditorAware<T> bean.
  • Alternatives: Hibernate @CreationTimestamp/@UpdateTimestamp, JPA @PrePersist/@PreUpdate callbacks, and Hibernate Envers (@Audited) for full history tables.

Interview questions

  • Compare the JPA inheritance strategies.
  • What is the difference between @MappedSuperclass and @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.SQL in dev, enable hibernate.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_size as a safety net, DTO projections for lists and reports, readOnly = true transactions.
  • Writes: SEQUENCE ids, hibernate.jdbc.batch_size (e.g. 50) with order_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. Never findAll() 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=validate or none in production with Flyway/Liquibase. Turn on hibernate.query.in_clause_parameter_padding for varying IN lists 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-auto setting do you use in production and why?