Learn. Practice. Feel prepared.
50 Spring Data JPA Interview Questions with real-world Scenarios
Prepare for Spring Data JPA interviews with real-world database challenges, Hibernate debugging scenarios, and performance optimization questions. Explore fetching strategies, transaction boundaries, concurrency control, and efficient pagination while tracking your interview readiness with instant scoring.
Top Spring Data JPA Interview Questions for Freshers and Experienced
50 Questions
Easy · Medium · Hard
Try answering from memory, then check the reference answer and rate yourself. Your notes are optional and are not automatically graded.
1 What responsibilities does Spring Data JPA handle, and which responsibilities remain with the JPA provider? easy
spring-data-jpahibernaterepositories
Reference answer
Spring Data JPA simplifies repository creation, query derivation, pagination, and integration with Spring transactions.
The JPA provider, such as Hibernate, manages entity persistence, dirty checking, SQL generation, and persistence contexts.
Spring Data JPA builds on JPA rather than replacing its underlying persistence mechanisms.
Did you know it?
2 How do CrudRepository, PagingAndSortingRepository, and JpaRepository differ in modern Spring Data JPA? easy
repositoriescrudpagination
Reference answer
CrudRepository provides basic persistence operations, while PagingAndSortingRepository adds pagination and sorting capabilities.
In modern Spring Data versions, paging repositories do not automatically inherit CRUD operations.
JpaRepository combines these capabilities and adds JPA-specific operations such as flush and batch deletion methods.
Did you know it?
3 What happens when save() is called on a new entity versus an existing entity? medium
entity-lifecyclesaveentity-manager
Reference answer
SimpleJpaRepository generally calls EntityManager.persist() for entities considered new and merge() for existing entities.
Persist makes a new entity managed, while merge copies detached entity state into a managed instance.
The entity returned by merge may be a different Java object from the supplied entity.
Explain how Spring Data determines whether an entity is new using version fields, identifiers, or Persistable.
Did you know it?
4 How does Spring Data JPA generate queries from repository method names? easy
query-derivationrepositoriesjpql
Reference answer
Spring Data parses repository method names into property paths, comparison operators, and sorting instructions.
For example, findByStatusAndCreatedAtAfter derives a query using status and createdAt predicates.
Derived queries are useful for simple conditions, while complex queries are often clearer with @Query or Specifications.
Did you know it?
5 What is the difference between a managed entity and a detached entity? easy
entity-statespersistence-contexthibernate
Reference answer
A managed entity belongs to an active persistence context, allowing Hibernate to track changes automatically.
A detached entity is no longer associated with that persistence context, so its changes are not automatically synchronized.
EntityManager.merge() can copy detached state into a managed entity.
Did you know it?
6 Why is the persistence context commonly described as a first-level cache? easy
first-level-cacheentity-managerpersistence-context
Reference answer
The persistence context maintains managed entity instances identified by their entity type and primary key.
Repeated EntityManager.find() calls for the same entity generally reuse the managed instance without another database lookup.
The cache is scoped to the persistence context and is distinct from an optional shared second-level cache.
Did you know it?
7 What is the purpose of @EntityGraph in a Spring Data JPA repository? easy
entity-graphfetchingrepositories
Reference answer
@EntityGraph specifies relationships to fetch for a particular repository operation.
It allows different use cases to request different association graphs without globally changing entity mappings.
For example, an order detail query can fetch customer information while a summary query leaves it unloaded.
Did you know it?
8 How does Page differ from Slice when retrieving paginated records? easy
paginationpageslice
Reference answer
Page provides content together with total element and page counts, which may require an additional count query.
Slice provides content and information about whether another slice exists, usually avoiding the total-count query.
Slice is useful for infinite scrolling where the complete result count is unnecessary.
Did you know it?
9 What does @Version contribute to entity concurrency control? easy
optimistic-lockingversioningconcurrency
Reference answer
@Version enables optimistic locking by tracking an entity's version across updates.
The persistence provider checks the expected version when writing changes and detects conflicting modifications.
This prevents silent overwrites when concurrent transactions modify the same entity.
Did you know it?
10 Why is @Transactional commonly placed on service methods rather than every repository method? easy
transactionsservice-layerrepositories
Reference answer
A service method often represents a complete business operation involving multiple repository calls.
Placing the transaction boundary at that level allows those operations to participate in one transaction.
It also separates business consistency requirements from individual persistence operations.
Did you know it?
11 An API retrieves 50 orders and then accesses each order's customer, resulting in 51 SQL queries. Why does this happen? medium
n-plus-onelazy-loadingquery-optimization
Reference answer
This is the N+1 query problem: one query loads the orders, and additional queries initialize their customer associations.
It commonly occurs when lazy relationships are accessed during DTO mapping or serialization.
Use a fetch join, EntityGraph, or DTO projection to retrieve the required data efficiently.
Describe how you would identify the extra queries using Hibernate SQL logs or query statistics.
Did you know it?
12 Why can FetchType.EAGER still produce N+1 queries when loading entities through JPQL? hard
eager-fetchingn-plus-onejpql
Reference answer
EAGER requires the relationship to be initialized but does not guarantee that JPQL will fetch it using a SQL join.
A query selecting root entities may trigger separate secondary queries to initialize eager associations.
Explicit fetch joins, EntityGraphs, or projections provide better control over the actual retrieval plan.
Explain why eager loading describes required initialization rather than guaranteeing a single SQL statement.
Did you know it?
13 A developer replaces lazy loading with JOIN FETCH for two List collections and encounters MultipleBagFetchException. What causes it? hard
multiple-bag-fetchjoin-fetchhibernate
Reference answer
Hibernate cannot safely fetch multiple bag collections simultaneously because their unordered, non-indexed rows create ambiguous collection reconstruction.
Joining multiple collections can also produce a large Cartesian product.
Fetch collections separately, use batching or subselect fetching, or redesign the query around DTOs.
Did you know it?
14 How would you optimize N+1 queries when fetching thousands of parent entities with child collections? hard
n-plus-onebatch-fetchinghibernate-performance
Reference answer
Avoid assuming that one enormous collection fetch join is always optimal because it can multiply result rows.
Consider Hibernate batch fetching with @BatchSize or hibernate.default_batch_fetch_size to initialize associations in groups.
Compare query counts, transferred rows, memory usage, and execution time against alternative fetch plans.
Did you know it?
15 How does Hibernate batch fetching differ from JOIN FETCH when resolving lazy associations? medium
batch-fetchingjoin-fetchlazy-loading
Reference answer
JOIN FETCH retrieves selected associations as part of the root query using joins.
Batch fetching loads associations through additional queries that group multiple entity identifiers.
Batch fetching can reduce N+1 behavior while avoiding the row multiplication caused by joining large collections.
Did you know it?
16 When would @Fetch(FetchMode.SUBSELECT) be preferable to batch fetching? hard
subselect-fetchinghibernatecollections
Reference answer
Hibernate subselect fetching can initialize collections for multiple previously loaded owners using a secondary query based on the owner-loading query.
It may work well when many owners and their collections are accessed together.
Batch fetching offers more predictable grouped loading when only a subset of associations is initialized.
Did you know it?
17 Why can paginating a JPQL query containing JOIN FETCH on a collection lead to serious performance problems? hard
paginationjoin-fetchhibernate
Reference answer
A collection fetch join multiplies root entity rows, making database-level pagination of root entities unreliable.
Hibernate may apply pagination in memory or reject the operation when configured to fail on collection-fetch pagination.
Use a two-step approach: paginate root entity IDs first, then fetch the required associations for those IDs.
Mention hibernate.query.fail_on_pagination_over_collection_fetch and explain the two-query solution.
Did you know it?
18 An endpoint returns duplicate parent records after joining a one-to-many relationship. How would you diagnose and resolve it? medium
join-fetchduplicatesjpql
Reference answer
A one-to-many join produces one SQL row for each matching child, repeating parent columns.
Check whether duplicates exist in SQL results, JPQL results, or the final DTO mapping.
Use appropriate DISTINCT semantics, grouping, or a query designed around the required result shape rather than blindly removing duplicates in Java.
Did you know it?
19 A REST response triggers additional SQL queries even though the service method already completed. What could explain this? hard
open-in-viewlazy-loadingserialization
Reference answer
If Open EntityManager in View is enabled, the persistence context can remain available during response serialization.
Jackson may access lazy associations and trigger queries outside the service transaction.
Disable Open EntityManager in View where appropriate and construct DTOs with explicit fetch plans inside the service layer.
Did you know it?
20 How would you prevent LazyInitializationException without enabling Open EntityManager in View? medium
lazy-initializationtransactionsdto
Reference answer
Determine which associations the use case actually requires and retrieve them within the transactional service boundary.
Use EntityGraphs, fetch joins, or DTO projections to load the required information.
Avoid exposing lazy entity graphs directly to serialization code after the persistence context closes.
Did you know it?
21 What happens when a managed entity is modified inside a transaction without explicitly calling repository.save()? medium
dirty-checkingpersistence-contexttransactions
Reference answer
Hibernate tracks changes to managed entities through dirty checking.
During flushing, it can generate UPDATE statements for modified persistent state without another save() call.
The changes become durable when the surrounding transaction successfully commits.
Did you know it?
22 Why can saveAndFlush() behave differently from save() when database constraints are involved? medium
flushsave-and-flushconstraints
Reference answer
save() delegates persistence operations without necessarily synchronizing all pending SQL immediately.
saveAndFlush() additionally flushes the persistence context, potentially exposing constraint violations earlier.
Flushing is not the same as committing; the transaction can still roll back afterward.
Did you know it?
23 A transaction inserts an entity and immediately executes a JPQL query. Can Hibernate flush the insert before commit? hard
flush-modejpqltransaction-lifecycle
Reference answer
Yes. With the usual AUTO flush behavior, Hibernate may synchronize pending changes before queries whose results could be affected.
This ensures queries observe relevant changes made within the transaction.
The exact flush behavior depends on the query, flush mode, identifier strategy, and persistence provider.
Did you know it?
24 A transactional method catches a repository exception and returns normally, but the caller receives UnexpectedRollbackException. Why? hard
rollback-onlytransactionsexception-handling
Reference answer
An inner transactional operation may mark the shared transaction as rollback-only after a failure.
Catching the exception does not automatically clear that rollback-only state.
When the outer method attempts to commit, Spring rolls back and can throw UnexpectedRollbackException.
Did you know it?
25 How do REQUIRED, REQUIRES_NEW, and NESTED transaction propagation differ? hard
transaction-propagationsavepointsspring-transactions
Reference answer
REQUIRED joins an existing transaction or creates one when none exists.
REQUIRES_NEW starts an independent transaction, suspending the existing one when present.
NESTED uses savepoints within an existing transaction when supported, allowing partial rollback without necessarily rolling back the outer transaction.
Explain that NESTED support depends on the transaction manager and underlying database capabilities.
Did you know it?
26 Why might @Transactional on a repository-related helper method not work when invoked from another method in the same class? medium
transactionalself-invocationaop
Reference answer
Spring's default transaction management relies on proxies that intercept calls entering a managed bean.
Self-invocation bypasses the proxy, so the invoked method's transaction metadata is not independently applied.
Move the transactional operation to another Spring-managed component or use TransactionTemplate.
Did you know it?
27 How can transaction isolation levels influence concurrent Spring Data JPA operations? hard
isolation-levelsconcurrencytransactions
Reference answer
Isolation levels control which changes from concurrent transactions may become visible during database operations.
READ_COMMITTED generally prevents dirty reads, while stronger isolation may reduce non-repeatable reads or phantom behavior.
Actual guarantees depend on the database, and isolation alone does not replace application-level concurrency controls.
Did you know it?
28 Two users load the same account balance and both update it. How does optimistic locking prevent a lost update? hard
optimistic-lockinglost-updateversion
Reference answer
A @Version field allows Hibernate to include the previously read version in the UPDATE condition.
The first successful update increments the version, causing a conflicting later update to affect no matching row.
Hibernate reports an optimistic locking conflict, allowing the application to retry or return a conflict response.
Did you know it?
29 When would pessimistic locking be more appropriate than optimistic locking? medium
pessimistic-lockingdatabase-locksconcurrency
Reference answer
Pessimistic locking is useful when concurrent modifications are frequent and conflicts must be coordinated before updates occur.
A repository method can use @Lock(LockModeType.PESSIMISTIC_WRITE) to request database-level locking.
It can reduce update conflicts but introduces lock waiting, contention, and deadlock risks.
Did you know it?
30 A Spring Data JPA application occasionally encounters database deadlocks during concurrent updates. How would you investigate and mitigate them? hard
deadlockslockingdatabase-concurrency
Reference answer
Inspect database deadlock reports to identify conflicting statements, locked rows, and transaction ordering.
Keep transactions short, access shared records in a consistent order, and ensure predicates use suitable indexes.
Retry deadlock victims with bounded backoff when the operation is safe to repeat.
Did you know it?
31 Why does @Version not automatically protect every bulk update executed through @Modifying? hard
bulk-updateoptimistic-lockingmodifying-query
Reference answer
JPQL bulk updates operate directly against database rows rather than updating managed entities individually.
They bypass ordinary entity dirty checking and do not automatically apply normal optimistic version checks.
Include explicit version conditions and increments when required, and handle persistence-context synchronization carefully.
Did you know it?
32 A repository bulk update succeeds, but a subsequent entity read returns an old value. What explains this behavior? hard
persistence-contextbulk-updatestale-data
Reference answer
Bulk JPQL operations bypass the managed entity state already stored in the persistence context.
An entity loaded before the bulk update can therefore remain stale.
Use clearAutomatically or explicitly refresh or clear affected entities, considering whether pending changes must be flushed first.
Did you know it?
33 Why does offset-based pagination become inefficient when querying millions of records? hard
offset-paginationkeyset-paginationindexes
Reference answer
Large offsets can force the database to scan or traverse many preceding index entries before returning the requested page.
Performance may deteriorate as the requested offset increases.
Keyset pagination uses the last retrieved sort values to seek directly into an indexed result set.
Did you know it?
34 How would you implement stable keyset pagination for records ordered by createdAt descending? hard
keyset-paginationcursorcomposite-index
Reference answer
Use a deterministic ordering such as createdAt DESC, id DESC to handle identical timestamps.
For the next page, filter using createdAt less than the cursor timestamp, or equal timestamps with id less than the cursor ID.
Create a matching composite index and return the final row's sort values as the next cursor.
Explain why a unique tie-breaker is necessary and how cursor conditions differ for ascending and descending order.
Did you know it?
35 Why can offset pagination return duplicate or missing records when new rows are inserted between page requests? medium
pagination-consistencyoffsetconcurrency
Reference answer
Offset pagination identifies positions rather than stable record boundaries.
Inserts or deletions before the current offset can shift records into different pages between requests.
Keyset pagination reduces these positional inconsistencies, although strict snapshot consistency requires additional database or application guarantees.
Did you know it?
36 A paginated repository query performs well when fetching content but spends most of its time counting records. How would you optimize it? medium
count-querypaginationquery-optimization
Reference answer
Inspect the generated count query and its execution plan for expensive joins, filters, or missing indexes.
Provide an optimized countQuery for complex @Query methods when appropriate.
Use Slice or cursor-based navigation if the user interface does not actually require total counts.
Did you know it?
37 How would you paginate parent entities while fetching their child collections without corrupting page boundaries? hard
two-step-paginationjoin-fetchcollections
Reference answer
First query a page of parent IDs using stable ordering and database-level pagination.
Then fetch the selected parents and required child associations using a second query restricted to those IDs.
Restore the original page order if the second query returns entities in a different sequence.
Did you know it?
38 How do interface-based projections and DTO constructor projections improve repository query performance? medium
projectionsdtoquery-performance
Reference answer
Projections allow repository queries to return selected fields instead of full entity graphs.
Interface projections expose properties through generated proxy objects, while constructor projections instantiate DTOs directly.
They can reduce unnecessary data retrieval, although nested projections may still introduce joins or broader entity loading.
Did you know it?
39 How would you build a search API with many optional filters without creating dozens of repository methods? medium
specificationscriteria-apidynamic-query
Reference answer
Use Spring Data JPA Specifications to compose predicates dynamically with the Criteria API.
Each optional filter contributes a predicate only when its input is present.
For more complex query models, Querydsl or a dedicated query service may provide better readability and control.
Did you know it?
40 What risks arise when dynamically constructing JPQL queries by concatenating user-supplied values? medium
jpql-injectionparameter-bindingquery-security
Reference answer
Concatenating untrusted values into JPQL can introduce injection vulnerabilities and malformed queries.
Use named parameters, positional parameters, or Criteria API parameter binding instead.
Validate dynamic identifiers such as sort fields against an allowlist because they cannot be treated like ordinary parameter values.
Did you know it?
41 A large import using saveAll() is unexpectedly slow. Does saveAll() automatically execute one bulk SQL insert? hard
save-alljdbc-batchingbulk-insert
Reference answer
No. saveAll() generally iterates through entities and delegates to save(), rather than generating a single bulk insert statement.
Enable JDBC batching where appropriate and use a compatible identifier generation strategy.
Process records in manageable transactions and periodically flush and clear the persistence context.
Did you know it?
42 Why can GenerationType.IDENTITY prevent Hibernate from batching insert statements effectively? hard
identity-generationjdbc-batchinghibernate
Reference answer
IDENTITY identifiers are generated by the database during insertion, so Hibernate commonly needs to execute inserts immediately to obtain generated keys.
This limits its ability to group entity inserts into JDBC batches.
Sequence-based generation with suitable allocation settings can support more effective batching on compatible databases.
Did you know it?
43 A batch processing job gradually consumes more heap memory despite processing records in small loops. What JPA behavior might cause this? hard
persistence-contextbatch-processingmemory
Reference answer
The persistence context retains references to managed entities and their snapshots until they are detached or the context closes.
Processing thousands of entities in one transaction can therefore accumulate memory.
Flush and clear periodically, reduce transaction size, or use streaming and stateless processing where appropriate.
Did you know it?
44 Why can deleteAll() and deleteAllInBatch() behave differently when entity lifecycle callbacks are involved? medium
bulk-deleteentity-callbacksjpa-lifecycle
Reference answer
deleteAll() typically removes entities individually, allowing normal entity removal semantics and lifecycle callbacks.
deleteAllInBatch() performs a bulk deletion that bypasses ordinary per-entity callbacks and JPA cascades.
Bulk deletion can also leave already managed entities inconsistent with the database until the persistence context is cleared.
Did you know it?
45 How can incorrect cascade settings accidentally delete more database records than intended? medium
cascadeentity-relationshipsdata-integrity
Reference answer
CascadeType.REMOVE propagates removal from a parent entity to associated entities according to the relationship mapping.
Applying it to shared relationships, especially many-to-many associations, can remove entities still needed elsewhere.
Use cascade removal only for relationships with clear ownership and dependent lifecycle semantics.
Did you know it?
46 What is the difference between orphanRemoval = true and CascadeType.REMOVE? medium
orphan-removalcascade-removerelationships
Reference answer
orphanRemoval removes a dependent entity when it is disconnected from its owning relationship.
CascadeType.REMOVE propagates deletion when the parent entity itself is removed.
Both can coexist, but they address different lifecycle events and should be used only when child ownership is well defined.
Did you know it?
47 How would you investigate a slow Spring Data JPA query that appears simple in repository code? hard
sql-analysisexecution-planquery-performance
Reference answer
Capture the actual SQL generated by Hibernate, including bound parameters and execution frequency.
Inspect the database execution plan for full scans, expensive joins, sorting, and index selection.
Check entity fetching, implicit joins, result size, and persistence-context overhead before optimizing the repository method.
Did you know it?
48 When should Hibernate's second-level cache be considered, and why is it not a universal solution to N+1 queries? hard
second-level-cachen-plus-onecaching
Reference answer
The second-level cache can reduce database reads for frequently accessed, relatively stable entities across persistence contexts.
It introduces cache invalidation, memory, and consistency considerations.
N+1 access patterns can still cause repeated cache lookups or misses, so efficient fetch plans remain essential.
Did you know it?
49 How would you ensure a Spring Data JPA integration test detects database-specific locking and transaction behavior? medium
testcontainerstransaction-testinglocking
Reference answer
Run tests against the same database engine used in production, preferably through Testcontainers.
Use separate transactions and concurrent execution to verify locking conflicts, isolation, and rollback behavior.
Avoid relying exclusively on in-memory databases because their SQL dialects and concurrency semantics may differ.
Did you know it?
50 You must design a high-traffic order listing API with millions of records, customer details, and optional filters. What Spring Data JPA architecture would you choose? hard
keyset-paginationfetch-strategiesscalability
Reference answer
Use indexed, composable predicates with DTO projections and deterministic keyset pagination for efficient navigation.
Avoid collection fetch joins in the paginated root query; fetch additional relationships separately when required.
Use read-only transactions where appropriate, monitor SQL plans and query counts, and apply caching only to suitable access patterns.
Structure the answer around query shape, indexing, N+1 prevention, transaction boundaries, and measurable performance trade-offs.
Did you know it?
0 / 0 answered