Spring Boot Interview Questions: Spring Data and Persistence
Reviewed by Mark Dickie · Last updated
5 questions on this page you can answer and see marked on the spot. Go to the first one
Spring Boot persistence is the layer where Spring Data repositories, JPA entities, and @Transactional boundaries meet a relational database. Interviewers use it to check whether you can follow a repository call down to the SQL it produces. Expect questions on transaction proxies, lazy loading, and how derived query methods turn into queries. Candidates who can explain why a query runs twice, or why a rollback never happened, tend to get further than those who only know the annotations.
What does a Spring Data persistence interview test?
| Topic | What to be able to explain |
|---|---|
| @Transactional propagation | REQUIRED joins the caller's transaction, while REQUIRES_NEW suspends it and commits on its own |
| Self-invocation | A @Transactional method called from another method in the same class skips the proxy, so no transaction starts |
| Open Session in View | spring.jpa.open-in-view defaults to true, which keeps the Hibernate session open while the view renders |
| N+1 queries | A lazy collection loaded inside a loop issues one extra SELECT per parent; @EntityGraph or JOIN FETCH removes them |
| Optimistic locking | A @Version column makes an UPDATE fail when the row changed after it was read |
| Derived queries | findByLastNameAndAgeGreaterThan is parsed from the method name at startup, and malformed names fail the context |
How do you practise these topics before an interview?
- Create an app with spring-boot-starter-data-jpa and an in-memory H2 database.
- Map a Parent entity to a Child with @OneToMany, save a few parents, then load them and read the SQL log to see the N+1 pattern.
- Call a @Transactional method from inside its own class, then check the log for whether a transaction began.
- Add a @Version field, update the same row from two sessions, and note the failure Spring raises.
- Add an @EntityGraph to the parent repository method and compare the statements logged before and after.
Key facts
- Tarmac has 27 Spring Boot interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
- Tarmac tracked 410 job postings asking for Spring Boot in November 2026.
- Roles asking for Spring Boot advertise a median base salary of £75,000, across 155 job postings as of November 2026.
- Tarmac last reviewed these Spring Boot interview questions on 23 November 2026.
At a glance
| Questions | 10 shown · 27 in the bank |
|---|---|
| Difficulty | 1–5 of 5 |
| Formats | Multiple choice, Ordering, Multiple answer, Code output, True / false, Find the bug, Short answer, Fill in the blank, Flashcard |
What you'll review
- entity relationships and mapping
- hibernate orm fundamentals
- transactions and transactional
Practice questions
Try one before you open the answer. Pick an option and press Check; it's marked on the spot.
In a bidirectional JPA relationship between Order (one) and OrderItem (many), where Order has @OneToMany(mappedBy = "order") and OrderItem has @ManyToOne with @JoinColumn(name = "order_id"), which side owns the foreign key column in the database?#
Options
Show answer
In a bidirectional JPA one-to-many mapping, the many side owns the foreign key. The @ManyToOne entity with @JoinColumn writes the column, while the @OneToMany side using mappedBy is only the inverse side that Hibernate reads for navigation.
The owning side of a bidirectional association is the side without mappedBy. In this mapping, the OrderItem entity carries @ManyToOne and @JoinColumn(name = "order_id"), so the order_id column lives in the order_item table and Hibernate uses that field to write the relationship. The Order collection marked with mappedBy is the inverse side: it reads the association but does not control the column. The option claiming the parent owns the key is wrong because mappedBy explicitly points away from it; the option claiming both sides hold a column is wrong because only one foreign key column is created; and the option about a list column in the parent table describes a collection-of-basic-values mapping, not this relationship.
Order these JPA/Hibernate entity lifecycle stages of a single Book object, from first to last, as it moves through a typical flow of creating it, saving it in a transaction, and then closing the persistence context.#
Put these in order
Show answer
The order is transient, managed, then detached. A new entity created with new is transient, calling EntityManager.persist() makes it managed by the persistence context, and closing that context leaves the entity detached.
An object created with new Book() has never been associated with a persistence context, so it is transient. Calling persist() registers it with the current persistence context, making it managed. When the persistence context is closed at the end of the unit of work, the entity is no longer tracked and becomes detached. Each step can only follow the previous one, so the order is transient, managed, detached.
Which of the following statements about JPA entity relationship mapping (as used in Spring Data JPA with Hibernate) are correct? Select all that apply.#
Options
Pick every one that applies.
Show answer
In JPA, the side marked with mappedBy is the inverse side that does not own the foreign key. By default, @ManyToOne associations load eagerly, while @OneToMany associations load lazily. The many side always owns the join column, so mappedBy cannot make a @ManyToOne side the owner.
The side marked with mappedBy is the inverse (non-owning) side, so the foreign key is written only through the other side, which holds the join column. By JPA specification defaults, @ManyToOne is EAGER and @OneToMany is LAZY. Placing mappedBy on the @ManyToOne side is invalid, because the many side always owns the foreign key, and the owning side is the one without mappedBy.
Assume this method runs inside a single active transaction (one persistence context, Hibernate as the JPA provider), and an Author entity with id 1 exists in the database. The entity is not detached or cleared between calls. What does the program print to standard output?#
@Transactional
public void run(EntityManager em) {
Author a1 = em.find(Author.class, 1L);
Author a2 = em.find(Author.class, 1L);
Author a3 = em.getReference(Author.class, 1L);
System.out.println(a1 == a2);
System.out.println(a1 == a3);
}Show answer
true
true
Hibernate keeps one managed instance per id in the persistence context (the first-level cache). The first em.find loads the Author and stores it in the context. The second em.find with the same id is served from that context and returns the same Java object, so a1 == a2 is true without a second SELECT. em.getReference also checks the persistence context first and returns the already-managed instance rather than creating a proxy, so a1 == a3 is true. Both lines therefore print true.
In a Spring Boot application using Spring's default proxy-based @Transactional support (no AspectJ weaving, default rollback rules), which of the following statements are true? Select all that apply.#
Options
Pick every one that applies.
Show answer
Spring's @Transactional rolls back by default only on unchecked exceptions (RuntimeException, Error). Checked exceptions commit unless you set rollbackFor, such as rollbackFor = Exception.class. With proxy-based AOP, self-invocation through this skips the proxy, so no transactional behavior is applied to that call. The default propagation is REQUIRED, not REQUIRES_NEW.
Spring's default rollback rules roll back only on unchecked exceptions (RuntimeException and Error); checked exceptions commit unless configured otherwise, which is exactly what rollbackFor = Exception.class changes. Because proxy-based AOP intercepts only calls arriving through the proxy, a self-invocation via this skips the transactional advice. The default propagation is REQUIRED (join an existing transaction or create one), not REQUIRES_NEW, so that statement and the checked-exception rollback statement are false.
In a bidirectional JPA mapping, Order has @OneToMany(mappedBy = "order", cascade = CascadeType.ALL) List<Item> items and Item has @ManyToOne @JoinColumn(name = "order_id") Order order. If you call order.getItems().add(item) and save the Order without calling item.setOrder(order), the order_id column of the saved Item row will be set to the new order's id.#
Options
Show answer
No. In a bidirectional JPA mapping, only the owning side, the @ManyToOne field with @JoinColumn, controls the foreign key. Adding an item to the parent's mappedBy collection without setting the item's order reference leaves order_id NULL, even when cascading persists the item.
The side marked mappedBy is the inverse side, and Hibernate ignores it when writing the foreign key. Only the owning side, the @ManyToOne field annotated with @JoinColumn, determines the order_id value. Cascading persists the Item row, but because item.order was never assigned, order_id is written as NULL. The fix is to set the back-reference on the owning side, typically through a helper method that updates both sides of the association.
A JPA entity is added to a HashSet before it is persisted. After em.persist(tag) assigns the id, tags.contains(tag) can return false for the very same object. The id is generated by GenerationType.IDENTITY, so it is null until persist. Which line of the entity is the bug? Answer with the line number of the single buggy line.#
@Entity
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public Tag() {}
public Tag(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
return this == o;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}Show answer
The bug is on line 18.
The bug is line 18, the hashCode that is computed from the id. While the tag is transient the id is null, so the set files the object under the hash of null. After persist assigns the id, hashCode returns a different value, but the HashSet still holds the object in the bucket for the old hash. contains computes the new hash and searches that bucket, so it can miss the object even though equals (identity, on line 13) returns true. Whether it misses depends on whether the new hash maps to the same bucket, so the failure is possible rather than guaranteed. equals is not the bug: identity comparison is consistent for the same object. A fix is to return a hash that does not change across persistence, such as getClass().hashCode().
In a Spring Boot app using Spring Data JPA (Hibernate 6), the mapping is:#
Show answer
The order_id column is written as NULL. The Order side is the inverse side because of mappedBy = "order", so Hibernate ignores its collection when writing foreign keys; only the owning side, OrderLine.order, controls the column. Cascade.ALL does insert the line, but the link is lost. The fix is to set line.order = order, ideally in an addLine helper on Order that updates both sides of the relationship.
The mappedBy attribute marks the Order.lines collection as the inverse (non-owning) side of a bidirectional one-to-many. Hibernate writes foreign keys only from the owning side, which here is the @ManyToOne field OrderLine.order. Adding the line to the collection therefore has no effect on the order_id column. Cascade.ALL ensures the new OrderLine is inserted during flush, so the row exists but its order_id is NULL. Setting line.order = order (preferably through a helper method that maintains both sides) makes the owning side reference the order, so the foreign key is written correctly.
In Spring Boot with default proxy-based @Transactional, OrderService.place() (default propagation) calls auditService.log() on another bean. log() is also @Transactional with default propagation REQUIRED. log() throws a RuntimeException, and place() catches it and returns normally. When the transaction manager tries to commit, it throws _____, because the inner method marked the shared physical transaction rollback-only. To let log() fail without affecting the outer transaction, annotate it with @Transactional(propagation = Propagation._____). That suspends the outer transaction and runs log() in its own independent physical transaction.#
Show answer
In Spring Boot with default proxy-based @Transactional, OrderService.place() (default propagation) calls auditService.log() on another bean. log() is also @Transactional with default propagation REQUIRED. log() throws a RuntimeException, and place() catches it and returns normally. When the transaction manager tries to commit, it throws **UnexpectedRollbackException**, because the inner method marked the shared physical transaction rollback-only. To let log() fail without affecting the outer transaction, annotate it with @Transactional(propagation = Propagation.**REQUIRES_NEW**). That suspends the outer transaction and runs log() in its own independent physical transaction.
With REQUIRED, the inner method joins the outer physical transaction, so both methods share one transaction. When a RuntimeException leaves the inner proxy, the interceptor marks that shared transaction rollback-only, even though the outer code catches the exception. When the outer method then commits, the manager sees the rollback-only flag, rolls back, and throws UnexpectedRollbackException so the caller isn't misled into thinking the commit worked. REQUIRES_NEW suspends the outer transaction and opens a separate physical transaction for the inner call. A rollback there doesn't mark the outer transaction, so after catching the exception the outer transaction can still commit. (NESTED uses savepoints and is driver-dependent, and it isn't supported with JPA's transaction manager, so the wording asks for an independent physical transaction.)
In Spring Boot 3 with Hibernate 6, a JPQL query using JOIN FETCH on two List collections of the same entity (for example select p from Parent p join fetch p.childrenA join fetch p.childrenB) throws MultipleBagFetchException. Why does Hibernate refuse this, and name two distinct ways to resolve it while still loading both collections.#
Show answer
Why: both Lists without @OrderColumn are bags (duplicates allowed, no index or uniqueness), so the join multiplies rows into a Cartesian product per parent, and Hibernate cannot reliably tell genuine duplicate elements from rows created by the join when assembling the two bags. Two fixes: (1) change one of the collections from List to Set so only one bag remains in the fetch; (2) do not join-fetch both in one query, instead fetch one collection with JOIN FETCH and load the other with a separate query in the same persistence context.
Hibernate permits at most one bag in a single fetch because a join of two bags yields a Cartesian product of rows, and bags have no positional index or uniqueness that would let Hibernate map each row back to the correct elements of each collection without ambiguity. The first fix works because a Set is not a bag: with only one bag left, the fetch no longer triggers the exception, and the Set's uniqueness semantics handle the duplicated rows. The second fix works because each query fetches only one bag, so no multiplication occurs; the second collection is then populated within the same persistence context. Note that an indexed List from @OrderColumn is also not a bag and is accepted in a fetch, but it still multiplies rows, so it is not offered here as a fix.
Related interview questions
Job market
See spring-boot salaries and hiring demand from live job postings.
The other 17 questions
This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 17 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.
Free · the whole bank · 100 answers per 30 days, each marked with written feedback