Spring Data JPA – 20 Production Scenarios (with Answers)

Spring Data JPA transaction behavior is easy to describe incorrectly because the annotation is only one part of the picture. Proxies, transaction managers, database connections, persistence contexts, flush timing, and database-specific locking rules all affect the outcome.

This article frames the issues senior Java developers are expected to reason about: how propagation changes transaction boundaries, how isolation interacts with JPA and different databases, why rollback decisions can surface later, and how optimistic locking protects—or fails to protect—concurrent updates.

All 20 answers below are free. Want the full set, every answer with a worked example?

Java Spring Boot & Microservices Interview Q&A (200 Qs)

Get the guide

Section 1: Propagation Traps

1. Orders roll back, but audit rows remain. How can REQUIRES_NEW cause this split?

REQUIRES_NEW suspends the order transaction and starts a separate physical transaction for the audit insert. The audit transaction can commit successfully, after which the suspended order transaction can still roll back, leaving an audit row for an order that never committed.

@Transactional
public void placeOrder(OrderCommand command) {
    orderRepository.save(createOrder(command));
    auditService.record("ORDER_CREATED"); // REQUIRES_NEW
    chargePayment();                       // later failure
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(String event) {
    auditRepository.save(new AuditEvent(event));
}

Spring suspends the outer transaction, including its resources, then obtains a transaction and usually a separate persistence context for the audit call. When that inner transaction commits, its data is durable independently of the outer transaction. A later exception, deadlock, constraint violation, or rollback-only marker affects only the outer transaction. The audit row may therefore describe an attempted action, not a committed business fact; that distinction should be explicit.

Useful production signals include:

  • Transaction debug logs showing suspension and a new transaction, correlated with a request ID and transaction name.
  • Different database connection identifiers for the order and audit statements, plus an outer rollback after the audit commit.
  • Audit records containing an event status or correlation key that cannot be matched to a committed order.

Choose the boundary deliberately:

  1. If the audit is part of the business invariant, use REQUIRED so it commits or rolls back with the order.
  2. If the audit must survive failure, model it as an independent failure/audit event and record that it represents an attempt; make duplicate handling and ordering explicit.
  3. For reliable post-commit publication, store an outbox row in the order transaction and publish it asynchronously after commit. This avoids an independent audit commit, but requires retry, deduplication, and cleanup handling.

Interview takeaway: REQUIRES_NEW is appropriate only when the independent commit is intentional; otherwise the audit must share the order transaction or use an outbox.

2. Why can Propagation.REQUIRED mark the outer transaction rollback-only?

Propagation.REQUIRED does not create a second transaction when one already exists: it joins the caller’s transaction. If the participating method fails in a way that marks that transaction rollback-only, catching the exception in the outer method does not make the transaction committable; the outer commit normally ends with UnexpectedRollbackException.

@Transactional
public void process() {
    orderRepository.save(order);
    try {
        inventoryService.reserve(order); // REQUIRED, joins this transaction
    } catch (InventoryException ex) {
        log.warn("Reservation failed", ex);
    }
    // Commit attempt: UnexpectedRollbackException
}

Spring maintains one physical transaction but can have several logical transaction scopes. An inner REQUIRED scope that encounters a runtime exception, or an exception configured for rollback, calls the transaction manager’s rollback-only operation. Some persistence failures, such as a failed flush or constraint violation, can also make the transaction unusable. The outer scope may continue executing because the exception was caught, but the transaction manager refuses a normal commit to prevent partial success. This is different from an inner savepoint: REQUIRED has no independent rollback boundary.

Check for:

  • The original exception in logs before the final UnexpectedRollbackException; the final exception is often only the symptom.
  • @Transactional on the actual Spring bean method. Self-invocation does not pass through Spring’s proxy, so the expected interceptor may not run.
  • Rollback rules, including rollbackFor and noRollbackFor, and flush timing. JPA may flush at commit rather than at save.

Fix it by making the business outcome explicit:

  1. Let the original exception propagate when the whole operation must fail.
  2. If recovery is valid, handle it in a separate transaction boundary, commonly a deliberately chosen REQUIRES_NEW operation, and accept its independent-commit semantics.
  3. If partial rollback is required inside one database transaction, evaluate NESTED with a supported transaction manager and JDBC savepoints; JPA state still needs careful handling.

Interview takeaway: With REQUIRED, a caught inner failure can leave the single shared transaction rollback-only, so recovery requires a real boundary, not merely a catch block.

3. How can Propagation.REQUIRES_NEW exhaust a connection pool under load?

REQUIRES_NEW suspends the caller but does not release its database connection. The inner transaction needs another connection, so a request with one suspended outer transaction and one active inner transaction can consume two pool entries; enough concurrent nesting can exhaust the pool and make all callers wait or time out.

request 1:  [outer connection held] -- suspend -- [inner connection]
request 2:  [outer connection held] -- suspend -- [inner connection]
request N:  [outer connection held] -- suspend -- [waiting for inner]

The risk is approximately the maximum simultaneous connection demand per request multiplied by concurrency, not just the number of application threads. Multiple REQUIRES_NEW calls can increase that demand further, and an inner call can itself invoke another independent transaction. A pool may therefore be configured with enough connections for ordinary requests but not for the suspended-transaction peak. If every worker holds an outer connection while waiting for an inner connection, the system can deadlock at the pool level until connection acquisition times out. The database may show fewer active statements than expected because requests are blocked before they reach it.

Production evidence includes:

  • Pool active, idle, pending, and acquisition-timeout metrics, especially a rise in pending borrowers.
  • Thread dumps showing request threads inside connection acquisition while holding an outer transaction.
  • Transaction and connection IDs showing an outer connection retained during an inner transaction; enable transaction/pool logging carefully because SQL logging is expensive.

Reduce the risk deliberately:

  1. Avoid REQUIRES_NEW inside long-running or high-concurrency transactions when the work can share the outcome.
  2. Keep the outer transaction short and move independent work outside it where the business contract permits.
  3. Size the pool for measured peak nesting and database capacity, with bounded timeouts. Increasing the pool alone can overload the database and does not fix long transactions.
  4. Use a separate, bounded executor or datasource only when its isolation and capacity are designed explicitly; asynchronous execution also changes ordering, error propagation, and security context behavior.

Interview takeaway: Count connections held by suspended transactions when sizing capacity; REQUIRES_NEW can turn one request into multiple simultaneous pool borrowers.

4. Why can Propagation.NESTED fail with JPA despite database savepoint support?

Database savepoint support is not enough for JPA NESTED propagation. Spring must have a transaction manager that can create JDBC savepoints, and the JPA persistence context must remain consistent with a partial database rollback; standard JPA does not define nested transactions or savepoints, so the call may be rejected or behave unsafely.

@Bean
JpaTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager tm = new JpaTransactionManager(emf);
    tm.setNestedTransactionAllowed(true); // JDBC savepoints; not standard JPA nesting
    return tm;
}

With JpaTransactionManager, nested transactions are not enabled by default. Enabling them permits savepoint-based behavior for JDBC access when the driver and connection support savepoints, but it does not turn JPA into a nested-transaction API. A rollback to a savepoint changes database state while managed entities, dirty checking, pending inserts, and the first-level cache may still reflect work that was rolled back. Flush timing can make the result surprising. With a JTA transaction manager, nested propagation is generally not available; the transaction manager may reject it rather than emulate it. Exact behavior depends on Spring, the transaction manager, provider, driver, and resource participation.

Diagnose the actual boundary:

  • Confirm which PlatformTransactionManager Spring selected and whether nested transactions are allowed.
  • Verify driver savepoint support and inspect transaction-manager logs for savepoint creation or NestedTransactionNotSupportedException.
  • Check whether the operation uses JPA entities, direct JDBC, or both, and whether the EntityManager is cleared or refreshed after a partial rollback.

Prefer one of these designs:

  1. Use REQUIRED when all work should succeed or fail together.
  2. Use REQUIRES_NEW when an independent commit is the real requirement, accepting extra connections and separate-transaction semantics.
  3. For true partial rollback, isolate the savepoint-sensitive work in a JDBC-oriented component, or redesign into smaller transactions and explicitly reload state after rollback. Test the exact provider and database combination rather than inferring behavior from database capability alone.

Interview takeaway: NESTED is a transaction-manager and resource capability, not a portable JPA feature; a database savepoint by itself does not make managed entity state safe.

5. Tests pass alone but fail together. How can test transaction boundaries hide the bug?

Spring’s test framework commonly wraps each test method in a transaction and rolls it back afterward. That outer test transaction can make a REQUIRED service appear correct while production invokes it without a caller transaction, and it can hide or create contamination through REQUIRES_NEW commits and cached JPA state.

@SpringBootTest
@Transactional // test transaction surrounds the service call
class OrderTests {
    @Test
    void failureIsHandled() {
        orderService.placeOrder(command); // REQUIRED joins test transaction
    }
}

A test calling a REQUIRED method may never exercise its normal top-level transaction boundary: the method joins the test transaction, and all its work is rolled back by the test listener. In production, the same method may start and commit its own transaction, flush at a different point, or throw UnexpectedRollbackException only at the caller’s commit. Conversely, a REQUIRES_NEW method commits despite the test transaction’s rollback, leaving rows for later tests. The same persistence context can also return an in-memory managed entity without querying the database, masking visibility and flush problems. Context caching, @Commit, @Rollback(false), and incomplete cleanup add more order dependence.

Make the boundary visible and reproduce the failure:

  1. Log transaction activity, connection identity, SQL, and test method names; explicitly flush and clear the EntityManager before assertions that are meant to verify database state.
  2. Run the relevant integration test without a test transaction, or place the transaction around the same production-level entry point rather than around every assertion.
  3. Use committed fixtures and deterministic cleanup when testing independent transactions. Include a test proving that a REQUIRES_NEW row survives an outer rollback if that is the contract.
  4. Check annotations such as @Commit, @Rollback, and @DirtiesContext, and avoid relying on test execution order.

A test that passes alone but fails in a suite often indicates leaked committed data, shared application context state, or a transaction boundary that differs between the test and production—not necessarily a random database failure.

  • A REQUIRES_NEW operation can commit outside the test rollback, so later tests may observe its rows unless they clean up committed state.
  • Cached entities, mocks, static state, and reused application contexts can preserve observations from an earlier test even when the test transaction itself was rolled back.

Interview takeaway: Test with the same transaction boundary as production, because a framework-managed test transaction can both hide rollback bugs and leak independent commits.

Section 2: Isolation Behavior

6. Deadlocks appear after a database upgrade. How can isolation choices expose them?

An upgrade can expose deadlocks because isolation determines which rows or ranges remain locked, while the new database version may also change defaults, query plans, or lock acquisition order. A deadlock is not proof that isolation is incorrectly configured: two transactions can deadlock even at READ_COMMITTED if they lock the same resources in opposite orders.

Typical changes that make the problem visible include:

  • MySQL InnoDB REPEATABLE_READ can take next-key locks on index ranges, blocking inserts as well as updates. READ_COMMITTED usually reduces gap locking, except for cases such as foreign-key checks and duplicate-key checks.
  • A new plan may scan more rows, use a different index, or hold locks longer. Missing or less selective indexes amplify this effect.
  • Higher isolation, especially SERIALIZABLE, adds predicate or serialization protection and therefore increases waiting and abort opportunities.
  • Foreign-key checks, triggers, and secondary-index updates can acquire locks that application code does not explicitly request.

Diagnose and fix it in this order:

  1. Capture the database deadlock report, not only the Java exception. PostgreSQL exposes details through its server log and pg_locks; InnoDB reports the latest deadlock through SHOW ENGINE INNODB STATUS. Correlate SQL, transaction IDs, indexes, and application trace IDs.
  2. Compare isolation, execution plans, indexes, and transaction duration before and after the upgrade.
  3. Make all code paths acquire shared resources in a consistent order, add appropriate indexes, and keep transactions short. Retry the whole transaction for a transient deadlock or serialization failure, with bounded backoff.
  4. Lower isolation only for a workload that can tolerate weaker guarantees; this reduces locking but does not replace correct lock ordering.
try {
    transactionTemplate.execute(status -> service.transfer(from, to));
} catch (DeadlockLoserDataAccessException | CannotAcquireLockException ex) {
    // Retry the complete transaction, not just the failed statement.
}

The trade-off is straightforward: stronger isolation can prevent anomalies but increases contention, while lower isolation improves concurrency but shifts correctness to version checks, constraints, and application logic.

Interview takeaway: I would correlate the deadlock graph with the changed plans and isolation semantics, then fix lock ordering and transaction scope before weakening isolation.

7. Why can READ_COMMITTED still allow lost updates in JPA?

READ_COMMITTED prevents a transaction from reading another transaction's uncommitted data, but it does not prevent two transactions from reading the same committed version and then overwriting each other. In JPA, a normal entity update has no conflict predicate unless the entity uses optimistic versioning or an explicit locking strategy.

A common sequence is:

  • Transaction A and B both load Account with balance 100.
  • A changes it to 90 and flushes; B changes its stale in-memory value to 80 and flushes later.
  • Both updates are committed, so B's update silently replaces A's change. READ_COMMITTED made each read legal; it did not compare the version that was read.
  • Hibernate often updates all mapped columns by default. @DynamicUpdate can reduce overwritten columns, but it does not detect a conflicting update to the same row. JPQL bulk updates bypass the persistence context and need explicit care.
@Entity
class Account {
    @Id
    Long id;

    @Version
    long version;

    BigDecimal balance;
}

// Hibernate includes the version in the UPDATE predicate:
// update account set balance=?, version=?
// where id=? and version=?

To diagnose and correct it:

  1. Inspect generated SQL and confirm that updates contain a version predicate. Check whether the entity is detached, whether a bulk update is involved, and whether the transaction actually spans load through flush.
  2. Add @Version to the entity and treat OptimisticLockException or Spring's translated ObjectOptimisticLockingFailureException as a conflict.
  3. Retry by starting a fresh transaction and reloading state, or report a conflict to the caller. For arithmetic changes, prefer an atomic SQL update such as set balance = balance - ? where id = ? and balance >= ?, and check the affected-row count.
  4. Use PESSIMISTIC_WRITE only when conflicts are frequent enough to justify blocking.

A version column also protects against stale detached updates, because the old version no longer matches after another transaction commits. It does not automatically protect native SQL or bulk JPQL unless those statements implement an equivalent predicate and the persistence context is handled correctly.

Interview takeaway: READ_COMMITTED protects visibility, not read-modify-write integrity; JPA needs @Version, an atomic statement, or an explicit pessimistic lock.

8. How do PostgreSQL and MySQL differ when the same isolation level is set?

The same JDBC isolation name does not guarantee identical behavior because PostgreSQL and MySQL implement snapshots and locking differently. The biggest practical trap is that PostgreSQL defaults to READ_COMMITTED, while InnoDB defaults to REPEATABLE_READ, and even matching labels have different effects on locking reads and serialization.

Important differences for InnoDB and PostgreSQL are:

  • At PostgreSQL READ_COMMITTED, each statement gets a fresh snapshot, so two selects in one transaction can see different committed data. At InnoDB READ_COMMITTED, consistent reads also use statement-level snapshots, but InnoDB's locking and foreign-key behavior still matter.
  • PostgreSQL REPEATABLE_READ uses one transaction snapshot and can abort a transaction when its snapshot-isolation rules cannot safely proceed. InnoDB REPEATABLE_READ uses a consistent snapshot for ordinary reads and commonly uses next-key locks for locking operations and range protection.
  • PostgreSQL SERIALIZABLE uses predicate-style SSI and reports serialization failures. InnoDB SERIALIZABLE makes ordinary reads more locking-oriented. Both require retry handling, but the blocked or aborted statement can differ.
  • SELECT ... FOR UPDATE is a current, locking read rather than an ordinary snapshot read in both systems, subject to each engine's lock and index rules.
-- PostgreSQL: statement-level visibility at READ COMMITTED
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

-- InnoDB: inspect the actual session setting
SELECT @@SESSION.transaction_isolation;

-- PostgreSQL: inspect the actual transaction setting
SHOW transaction_isolation;

When diagnosing a portability issue:

  1. Verify the storage engine, database version, session isolation, and transaction boundaries; a framework setting may be overridden by a connection pool or server default.
  2. Run the competing transaction scenario on both databases, including ordinary reads, FOR UPDATE, range predicates, and inserts into the range.
  3. Handle deadlock and serialization exceptions as retryable only when the entire transaction is safe to repeat.

The trade-off is portability versus engine-specific concurrency. Declare isolation deliberately, test the exact SQL and indexes, and do not infer semantics from the isolation label alone.

Interview takeaway: I would compare snapshot rules and locking reads on the actual engine, not assume that a matching JDBC isolation constant means matching behavior.

9. Why can EntityManager.flush() make a query see more changes than expected?

EntityManager.flush() synchronizes pending changes in the persistence context with the database; it does not commit them. Once those INSERT, UPDATE, or DELETE statements execute, a subsequent query in the same transaction can see those uncommitted changes, and Hibernate may also flush automatically before a query whose tables overlap the pending changes.

This can surprise developers because:

  • A managed entity is changed in Java, but the SQL may be delayed until explicit flush(), transaction commit, or a provider-selected auto-flush point.
  • With Hibernate's usual FlushMode.AUTO, JPQL or Criteria queries can trigger a flush when Hibernate detects relevant query spaces. The exact auto-flush behavior is provider and version dependent; explicit flush is the portable guarantee.
  • A flush can execute callbacks, constraints, database triggers, generated-key work, and optimistic-version updates earlier than expected. It can therefore fail before the method reaches its apparent write boundary.
  • The query sees the transaction's own writes. Other transactions normally cannot see them until commit, unless the database uses an unusual weaker visibility configuration.
entity.setStatus(Status.PAID);
entityManager.flush();       // SQL is issued now
List<Order> paid = entityManager.createQuery(
    "select o from Order o where o.status = :status", Order.class)
    .setParameter("status", Status.PAID)
    .getResultList();         // can include the flushed row

For diagnosis and control:

  1. Enable Hibernate SQL and bind-parameter logging, then identify the statement immediately before the query. Record the active flush mode and transaction boundary.
  2. Use explicit flush when later SQL must observe pending changes or when you want constraint and optimistic-lock failures at a known point.
  3. Use FlushModeType.COMMIT cautiously for read-heavy work, but verify query results because pending changes may not be flushed before the query. Separate read and write units of work when that is clearer.
  4. Remember that flushing does not make the operation durable or visible to other transactions; commit still controls that.

The persistence context may also return an already-managed object without querying, so application-visible state can come from both the first-level cache and the database. That is why SQL logs alone do not always explain every result.

Interview takeaway: flush() is an SQL synchronization boundary, not a commit, and it can make same-transaction queries observe pending changes earlier than expected.

10. How does @Lock(LockModeType.PESSIMISTIC_WRITE) change concurrent updates?

@Lock(LockModeType.PESSIMISTIC_WRITE) asks Spring Data JPA to apply a database write lock when it loads the matching entity, typically resulting in SQL such as SELECT ... FOR UPDATE where the dialect supports it. A competing transaction must usually wait, fail on a lock timeout, or encounter a deadlock until the first transaction commits or rolls back.

public interface OrderRepository extends JpaRepository<Order, Long> {
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select o from Order o where o.id = :id")
    Optional<Order> findForUpdate(@Param("id") Long id);
}

@Transactional
public void reserve(Long id) {
    Order order = repository.findForUpdate(id)
        .orElseThrow();
    order.reserve();
}

The important behavior and limits are:

  • The lock is held by the database transaction, not merely by the Java method or persistence context. The repository call must run inside an appropriate transaction, and the transaction must remain open while the protected read-modify-write operation occurs.
  • A second transaction requesting the same lock blocks or receives a database-specific timeout/deadlock exception. Configure and monitor lock timeouts according to the database and driver; JPA lock timeout hints are provider and database dependent.
  • The lock prevents competing locking operations and ordinary updates according to database rules, but it does not make unrelated bulk SQL safe. All code paths need to respect the same row or predicate protection.
  • Locking one row at a time can still deadlock if different paths acquire rows in different orders.

Use it deliberately:

  1. Confirm generated SQL, transaction scope, selected indexes, and the database's lock graph under concurrency.
  2. Keep the transaction short and acquire multiple locks in a stable order. Retry transient deadlocks or lock-timeout failures only when the whole operation is repeatable.
  3. Prefer @Version for low-contention workloads, because optimistic locking avoids blocking and detects conflicts at flush. Use pessimistic locking when waiting is preferable to conflicting work or when the decision depends on a row that must not change during the transaction.

Pessimistic locking changes contention from silent last-write-wins behavior into waiting or failure, but it does not remove the need for transaction design, timeout handling, and deadlock prevention.

Interview takeaway: PESSIMISTIC_WRITE reserves the database row for the transaction, so concurrent code waits or fails instead of freely performing a stale update.

Preparing for a full interview loop? Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)

Section 3: Rollback Surprises

11. A checked exception leaves data committed. Which rollback rule explains it?

By default, Spring rolls back for RuntimeException and Error, but not for checked exceptions. A checked exception therefore normally reaches the transaction interceptor as a successful completion, and the transaction manager commits unless the method declares a matching rollbackFor rule or explicitly marks the transaction rollback-only.

@Transactional(rollbackFor = IOException.class)
public void importFile(Path path) throws IOException {
    repository.save(batch);
    readAndValidate(path); // IOException now causes rollback
}

The important details are:

  • The default rule is rollback for unchecked exceptions and errors; checked exceptions are commit candidates.
  • rollbackFor matches an exception type, including subclasses. rollbackForClassName uses a name or pattern and is easier to match accidentally.
  • A checked exception caught inside the method does not trigger the interceptor at all. If its work must be undone, call TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(), or rethrow an exception covered by the transaction rule.
  • The rule applies when the exception exits the proxied transactional method. Self-invocation can bypass the proxy, so the annotation may never have been applied.

To diagnose and fix it:

  1. Check the actual exception class at the transaction boundary, not only its root cause, and inspect the transaction interceptor logs.
  2. Verify that the call goes through a Spring proxy and that the transaction annotation is on the effective public entry point.
  3. Choose the narrowest checked exception that should cause rollback, then add a focused rollbackFor rule and tests for both success and failure paths.

Interview takeaway: A checked exception is not a rollback signal in Spring by default, so declare the required rollbackFor policy or mark the transaction rollback-only explicitly.

12. Why can catching DataIntegrityViolationException still doom the transaction?

Catching DataIntegrityViolationException does not necessarily make the transaction usable again. The exception may already have caused Spring or the JDBC/JPA provider to mark the current transaction rollback-only, so a later commit rolls everything back and commonly reports UnexpectedRollbackException.

@Transactional
public void placeOrder(Order order) {
    try {
        orderRepository.saveAndFlush(order); // constraint checked here
    } catch (DataIntegrityViolationException ex) {
        auditRepository.save(new Audit("duplicate order"));
        // The surrounding transaction may already be rollback-only.
    }
}

Why this surprises teams:

  • Constraint violations can occur during an explicit flush, a query-triggered flush, or the transaction's final flush, rather than exactly at save.
  • Spring translates provider or JDBC exceptions into DataIntegrityViolationException, but translation does not clear the database transaction's failed state.
  • The persistence context can contain entities whose state no longer corresponds to the database. Continuing with more writes is therefore unsafe even if the Java exception was caught.
  • An outer transactional caller may receive UnexpectedRollbackException only when it tries to commit, hiding the original location unless it was logged.

Use one of these designs after confirming the failure:

  1. Let the exception escape and roll back the unit of work; handle it outside the transaction when possible.
  2. If the operation is optional, isolate it in a separate method with REQUIRES_NEW and invoke that method through a proxy. The inner transaction can roll back without poisoning the outer one.
  3. For expected duplicate or validation cases, check before writing or use an idempotency/constraint-aware design, while still treating the constraint as authoritative under concurrency.

Interview takeaway: Once a constraint failure marks the transaction rollback-only, catching the exception changes control flow but not the transaction outcome.

13. How do rollbackFor and noRollbackFor interact when both match?

When both rollbackFor and noRollbackFor match, Spring applies the strongest matching rule: the most specific exception type or pattern wins. Thus a specific noRollbackFor can override a broader rollback rule, while a specific rollbackFor can override a broad no-rollback rule.

@Transactional(
    rollbackFor = Exception.class,
    noRollbackFor = BusinessWarning.class
)
public void process() throws Exception {
    // BusinessWarning: commit candidate; another checked Exception: rollback
}

The mechanism and its limits are:

  • Spring builds rollback rules from the annotation and evaluates the thrown exception against them, including superclass matches.
  • A broad rollbackFor = Exception.class normally rolls back checked exceptions, but the more specific BusinessWarning exclusion wins in the example.
  • Do not create conflicting rules with the same specificity and assume a useful business meaning. Make the policy unambiguous instead of depending on declaration order or implementation details.
  • Name-based rules such as rollbackForClassName can match similarly named classes and nested classes; class-based rules are safer when the type is available.
  • This decision is made by the transaction interceptor when the exception leaves the transactional boundary. Catching the exception inside the method prevents the rule from being evaluated unless rollback-only is set explicitly.

To verify a production rule:

  1. Log the actual thrown class and the transactional method that received it; proxying and self-invocation can matter as much as the annotation.
  2. Write tests for the broad exception, the excluded subtype, and a sibling subtype. Assert both database state and any UnexpectedRollbackException from an outer transaction.
  3. Keep rollback policy close to the business boundary, and avoid using noRollbackFor to suppress failures that leave JPA state or database constraints unreliable.

Interview takeaway: The most specific matching rollback rule wins, so use narrow, non-conflicting rules and test the exception hierarchy explicitly.

14. Kafka messages exist, but the database rolls back. How do you prevent this inconsistency?

A database transaction and Kafka publication are separate resource commits, so one can succeed while the other fails. The usual reliable solution is a transactional outbox: write the business change and an outbox row in one database transaction, then publish the outbox row to Kafka with retries and idempotent handling.

@Transactional
public void createOrder(OrderCommand command) {
    Order order = orderRepository.save(Order.create(command));
    outboxRepository.save(OutboxEvent.orderCreated(order.getId()));
}

// Separate relay: claim unsent rows, publish, then mark sent.
// Consumers deduplicate by event id.

Why this prevents the observed inconsistency:

  • If the database rolls back, neither the order nor its outbox event exists. If it commits, the event is durable for a relay to retry.
  • The relay can crash after Kafka accepts a message but before marking the row sent, so duplicate publication is possible. Consumers must use a stable event ID and an idempotency store or naturally idempotent updates.
  • Use row claiming, leases, retry state, and a dead-letter or operational path for poison events. Keep payload versioning and ordering requirements explicit.
  • A Kafka transaction can make a Kafka read-process-write flow atomic within Kafka, but it does not by itself atomically commit a relational database. XA or vendor-specific coordination adds operational complexity and still needs careful recovery design.

A practical rollout is:

  1. Add the outbox table and insert its row in the same local transaction as the domain write.
  2. Run a durable relay that publishes with an event key and records delivery state only after successful publication.
  3. Make every consumer idempotent, monitor outbox age and retry failures, and reconcile database records against published event IDs.

Interview takeaway: Do not try to make ordinary database and Kafka sends appear atomic; persist the intent with the database and publish it reliably from an outbox.

15. How does TransactionTemplate expose setRollbackOnly decisions explicitly?

TransactionTemplate exposes the decision through its callback status: call status.setRollbackOnly() when the code has handled a condition but the whole transaction must still be undone. The callback can return normally, yet the transaction manager sees the rollback-only marker at completion and rolls the transaction back.

TransactionTemplate template = new TransactionTemplate(transactionManager);

Boolean saved = template.execute(status -> {
    repository.save(entity);
    if (!policy.allows(entity)) {
        status.setRollbackOnly();
        return false;
    }
    return true;
});
// saved may be false; the transaction was rolled back, not committed.

This is useful because:

  • The rollback decision is visible beside the business condition instead of being encoded indirectly in an exception type or annotation.
  • setRollbackOnly() marks the current transaction; it does not immediately undo SQL or guarantee that no later code runs in the callback.
  • If the template joins an existing transaction, the marker affects that enclosing transaction too. An inner template cannot independently commit a participating transaction.
  • If an outer caller later tries to commit a transaction marked rollback-only, the result can be UnexpectedRollbackException, depending on the transaction manager and propagation context.
  • A callback exception is still handled by the transaction template's normal rollback rules. Use setRollbackOnly() when normal return is intentional but commit is not.

To use it safely:

  1. Keep the callback focused on one transaction boundary and return a result that distinguishes accepted work from policy rejection.
  2. Set rollback-only before returning whenever handled validation or business logic means no database change may survive.
  3. Test both standalone execution and invocation inside an existing transaction; the latter reveals whether the decision unexpectedly rolls back the caller's work.
  4. If the rejected operation should be independent, use a separate transaction with an explicit propagation design rather than assuming nested template execution creates an independent commit.

Interview takeaway: With TransactionTemplate, setRollbackOnly() makes a handled-but-non-committable outcome explicit while preserving the surrounding transaction semantics.

Section 4: Optimistic Locking

16. Two requests both succeed, but one update disappears. How do you prove @Version is missing?

You prove @Version is missing by showing that Hibernate’s UPDATE statement has no version predicate and that two concurrent transactions both report one updated row. With optimistic locking configured correctly, the SQL includes where id = ? and version = ?; the second update affects zero rows and Hibernate raises an optimistic-locking exception.

@Entity
class Account {
    @Id
    private Long id;

    @Version
    private long version;

    private String status;
}

-- Expected shape with optimistic locking
update account
set status = ?, version = version + 1
where id = ? and version = ?

Diagnose it with evidence from both the mapping and the database:

  1. Inspect the deployed entity class, not only the source branch, and confirm exactly one supported @Version field is mapped and included in the persistence unit.
  2. Enable Hibernate SQL and bind-parameter logging briefly, or use a database audit trace. Compare concurrent updates: a versioned update contains the old version in its where clause and increments the version.
  3. Run a deterministic concurrency test with two transactions reading the same row, pausing at a barrier, and then updating. The correct result is one commit and one OptimisticLockException or Spring’s translated ObjectOptimisticLockingFailureException.
  4. Check row counts and application logs. Two successful updates with the same starting version, and no zero-row update, strongly indicate last-write-wins behavior rather than optimistic locking.

Also check for misleading evidence:

  • A native SQL update, JPQL bulk update, trigger, or another service may bypass the entity mapping.
  • A database log showing a version column is not enough; the predicate must compare the previously read version.
  • Adding @Version changes the update contract and can expose existing retry or conflict-handling bugs. Deploy the schema and application mapping together, then test stale writes before enabling the path broadly.

Interview takeaway: I would prove it from generated SQL: without version = ? in the update predicate and a zero-row conflict for the loser, @Version is not protecting that write.

17. Why does @Version not protect bulk JPQL updates?

@Version protects entity state transitions, not arbitrary bulk DML. A JPQL update is translated directly into SQL and does not load each entity, compare its in-memory version, increment @Version automatically, or invoke entity lifecycle callbacks.

@Modifying
@Query("update Order o set o.status = :status where o.createdAt < :cutoff")
int closeOldOrders(Instant cutoff, Status status);

That statement can change rows while managed Order objects in the current persistence context still contain the old status and version. A later flush may overwrite the bulk change, or the application may return stale data. Hibernate also cannot perform one optimistic check per entity because the operation is intentionally set-based.

Important consequences include:

  • Standard JPA bulk JPQL does not automatically add a version predicate or increment @Version. Hibernate has a versioned bulk-HQL extension, but that is provider-specific and still needs careful cache and persistence-context handling.
  • Bulk DML normally bypasses entity callbacks, dirty checking, and auditing code attached to entity updates.
  • Second-level and query caches can become stale unless the affected regions are invalidated or the operation is executed with suitable provider support.

Choose the behavior explicitly:

  1. Use ordinary entity loading and updates when each row needs optimistic conflict detection, callbacks, or per-row business rules. Flush in manageable batches if volume permits.
  2. For a set-based operation, add an explicit predicate and version increment where the business contract allows it, for example where status = :expectedStatus; inspect the affected row count and treat an unexpected count as a conflict.
  3. After the bulk operation, flush before it, then clear the persistence context with EntityManager.clear() or isolate the operation in a transaction whose entities are not reused. Evict affected cache regions when required.
  4. Document that a bulk command has different concurrency semantics from editing one entity.

Interview takeaway: Bulk JPQL is direct set-based SQL, so use entity updates for normal version checks or implement the predicate, version increment, and cache clearing explicitly.

18. How should an OptimisticLockException be handled after its transaction ends?

Handle OptimisticLockException as a failed transaction, not as a validation warning inside the same transaction. Once the flush or commit detects a stale version, the transaction is normally marked rollback-only; recover by rolling it back, starting a fresh transaction, rereading current state, and then deciding whether to retry or report a conflict.

@Retryable(retryFor = ObjectOptimisticLockingFailureException.class,
           maxAttempts = 3)
@Transactional
public void rename(long id, String name) {
    User user = repository.findById(id).orElseThrow();
    user.rename(name);
}

@Recover
public void conflict(ObjectOptimisticLockingFailureException ex,
                     long id, String name) {
    throw new ConflictException("The user changed; reload and retry", ex);
}

The exception may be raised during flush() or transaction commit, and Spring may translate the JPA exception into ObjectOptimisticLockingFailureException. Catching it inside the transactional method and continuing can produce an UnexpectedRollbackException at the boundary, because the transaction cannot be committed successfully.

A safe response pattern is:

  1. Let the exception cross the transaction boundary, or mark the transaction for rollback and handle it outside that boundary.
  2. For an automatic retry, invoke a new transaction on each attempt. A Spring retry annotation works through a proxy; self-invocation does not apply the interceptor. Do not reuse the stale entity or persistence context.
  3. Reread the row and reapply only an operation that is safe to repeat. Recalculate derived values and check business invariants after rereading.
  4. Stop after a bounded number of attempts. For interactive commands, return a conflict response such as HTTP 409 and let the client reload or merge.

Retries are not universally correct:

  • They can duplicate external side effects unless those effects are idempotent or moved behind an outbox.
  • A retry may hide a genuine contention or business conflict, so log the entity identifier, expected version, actual outcome, and attempt count.
  • A transaction that failed at commit has no reliable success result; do not send a success message before the boundary has committed.

Interview takeaway: After an optimistic conflict, discard the failed persistence context and either retry the reread-and-update operation in a new transaction or return a clear conflict.

19. How can a stale second-level cache entry trigger an optimistic locking conflict?

A stale second-level cache entry can supply an entity with an old version to a transaction, and that transaction then issues an update using the stale version. The database’s version predicate rejects it with a zero-row update, so the cache causes a visible optimistic conflict; it does not defeat the database guard or silently permit a lost update.

-- Database contains version 6
-- Node B read version 5 from its stale L2 cache
update customer
set name = ?, version = version + 1
where id = ? and version = 5;

-- Result: 0 rows; Hibernate raises an optimistic-lock exception

The usual sequence is that node A updates version 5 to version 6, but invalidation or replication to node B is delayed, lost, or misconfigured. Node B’s persistence context obtains version 5 from its cache and flushes it. A correct @Version check prevents corruption, but users may see avoidable conflicts or repeated retries.

Diagnose the path rather than assuming the database is wrong:

  1. Correlate the exception with the SQL predicate, entity identifier, and expected version. Confirm that the database row has already advanced.
  2. Compare second-level-cache hit, miss, put, and eviction metrics across nodes and inspect invalidation or replication logs.
  3. Check the entity’s cache concurrency strategy, provider configuration, cluster topology, and whether native or bulk updates bypass cache invalidation.
  4. Reproduce with cache enabled and disabled. If conflicts disappear when the region is disabled, investigate cache coherence rather than removing the version field.

Typical fixes are:

  • Use a provider-supported read-write or transactional cache strategy appropriate to the deployment, with reliable invalidation between nodes.
  • Disable second-level caching for highly contended entities when coherence cost exceeds its benefit.
  • Evict or refresh affected regions after bulk or native updates, and clear the persistence context so it does not retain stale managed instances.
  • Keep retry handling bounded; a retry should reread current state, not repeatedly reuse the cached object.

Interview takeaway: The stale cache explains why the old version was used, but the database version predicate still does its job by converting that stale read into a safe conflict.

20. Why does @TransactionalEventListener(AFTER_COMMIT) not run when commit fails?

@TransactionalEventListener(phase = AFTER_COMMIT) runs only after the transaction manager reports a successful commit. If flush or commit fails, including because of an optimistic-lock or constraint error, the transaction rolls back and there is no successful commit phase in which that listener can run.

@Component
class OrderEvents {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void sendConfirmation(OrderPlaced event) {
        // Runs only after the enclosing transaction commits successfully.
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
    public void recordRollback(OrderPlaced event) {
        // Runs when the enclosing transaction rolls back.
    }
}

The event is associated with a transaction synchronization when it is published inside an active transaction. Spring’s default fallbackExecution is false, so if no transaction exists, the listener is skipped rather than executed immediately. Also, AFTER_COMMIT is not a durable message queue: a process crash after the database commit but before listener execution can still lose the in-process notification.

Diagnose and design around the boundary:

  1. Log event publication, transaction outcome, and listener invocation with a correlation identifier. Confirm whether the event was published inside the intended transaction.
  2. Check the real failure point. JPA may discover a version conflict only at flush or commit, after the service method appeared to complete normally.
  3. Use AFTER_ROLLBACK for rollback-specific local cleanup, or AFTER_COMPLETION when code must observe either outcome; do not use those phases to pretend a failed commit succeeded.
  4. For a reliable integration event, write an outbox row in the same database transaction and let a separate relay publish it after commit.

One further trade-off matters: an AFTER_COMMIT listener runs after the original transaction is complete. If it must write to the database, give it a separate transaction, commonly through another proxied service with REQUIRES_NEW; an exception there cannot undo the already completed commit. Keep that work idempotent.

  • A listener that fails after a successful commit cannot roll back the already committed business transaction, so its failure needs independent logging, retry, or recovery handling.
  • For cross-service delivery, prefer an outbox or another durable coordination mechanism rather than relying solely on in-process AFTER_COMMIT execution.

Interview takeaway: AFTER_COMMIT means successful commit, not method completion, so a failed commit correctly suppresses it; use rollback handling or an outbox when the outcome must be reliable.

Key Takeaways

  • REQUIRES_NEW suspends the existing transaction and uses an independent transaction and usually an independent connection.
  • A REQUIRED method can mark the shared transaction rollback-only even when its exception is caught by the caller.
  • Nested transactions depend on savepoint support from the transaction manager, resource, and persistence technology; database support alone is not sufficient.
  • Holding an outer connection while starting REQUIRES_NEW work can exhaust a connection pool under concurrency.
  • READ_COMMITTED prevents dirty reads but does not by itself prevent lost updates.
  • JPA may flush pending changes before a query, so query results can reflect writes that have not yet committed.
  • Spring’s default rollback behavior targets unchecked exceptions and Error, while checked exceptions normally require an explicit rule.
  • Catching a persistence exception does not clear a transaction’s rollback-only state or make the persistence context safe to continue using.
  • Bulk JPQL updates bypass normal entity dirty checking and do not apply @Version checks automatically.
  • An optimistic-locking failure should normally be handled outside the failed transaction, often by retrying with a fresh persistence context.
  • @TransactionalEventListener(AFTER_COMMIT) is conditional on a successful commit and cannot compensate for a transaction that rolls back.
  • Reliable database-to-Kafka publication generally requires an outbox or another deliberately designed coordination strategy.

Frequently Asked Questions

What determines which transaction manager controls a repository call?

Spring resolves transaction advice through the configured transaction manager, the transaction annotation, and any qualifiers or explicit configuration. A JpaTransactionManager coordinates a JPA EntityManager, while a JDBC manager coordinates JDBC resources; they are not interchangeable in every scenario. When multiple managers exist, make the choice explicit and verify that the repository, datasource, and transaction boundary use the same resource model.

Should isolation be configured on every service method?

Usually not. Isolation is a concurrency policy and should be selected for a specific consistency requirement, not applied indiscriminately. Start with the database default, then raise or lower isolation only where the required behavior is clear. Also verify the database, driver, transaction manager, and connection pool actually honor the requested level, because unsupported or mapped levels can produce different effective behavior.

Is retrying a transaction always safe after a conflict?

No. A retry is appropriate only when the operation is designed to be repeatable and its external side effects are controlled. Re-run the database work in a new transaction and persistence context, use an idempotency key where needed, and avoid sending duplicate messages or charging an external system inside an operation that may be retried. Limit retries and record the final failure.

When should an application prefer an outbox over dual writes?

Use an outbox when a database change and a message publication must represent one business decision but the systems do not share a reliable atomic commit protocol. Store the event in the same database transaction as the state change, then publish it asynchronously and track delivery. Consumers should be idempotent because retries, redelivery, and process crashes remain possible.

How can a team verify transaction behavior in tests?

Use integration tests with the real transaction manager and a database engine that matches production behavior where locking matters. Assert committed state from a separate transaction, inspect rollback and propagation boundaries, and include concurrent tests for conflicts and deadlocks. Avoid relying only on a test-level transaction, because it can keep changes uncommitted and hide connection, visibility, or cleanup problems.

Conclusion

Reliable transaction design requires separating Java control flow from transaction and database state. A caught exception may still leave a shared transaction doomed, a successful method return may precede a failed commit, and an apparently safe update may have no version check at all. Treat propagation, isolation, flushing, rollback rules, messaging, and locking as one system. Then verify the assumptions with integration and concurrency tests that observe behavior from independent transactions, not just from the test thread’s persistence context.

Which question would you find the hardest? Tell me in the comments.

Explore More Java Interview Resources

Java Spring Boot & Microservices Interview Q&A (200 Qs)
https://topmate.io/logicbrace/2278363

Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)
https://topmate.io/logicbrace/2294498

Complete Java Full Stack Developer Kit (900 Qs: Core Java, Spring Boot & Microservices, Cloud/DevOps/System Design, React & Angular)
https://topmate.io/logicbrace/2306382

Spring Data JPA – 20 Production Scenarios (with Answers)

Post a Comment

0 Comments

Close Menu