Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
Chaturmind
← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 2–5 YearsSpring Boot In Depth & Scenarios
✓ FreeIntermediate· 7 min read

Spring Boot Data, Transactions & Caching — Interview Questions

The Spring cache abstraction and providers, implementing caching correctly, how Boot simplifies the data layer, transaction best practices, eviction vs expiration, pagination (offset and keyset), soft deletes with Hibernate 6, and structuring a user-management REST API.

Published September 25, 2026


How to use this lesson

Data-layer questions at this level expect production awareness: cache invalidation, transaction boundaries, N+1 queries, and pagination that doesn't fall over on page 10,000. Mention one failure mode per answer, and you'll stand out.

Q1. What caching mechanisms does Spring Boot provide?

Short answer: Spring's cache abstraction: annotations (@Cacheable, @CachePut, @CacheEvict, @Caching) applied through AOP proxies to bean methods, backed by a pluggable CacheManager. Boot auto-configures the provider it finds:

  • Caffeine: an in-process cache with size, TTL and stats. The best local choice.
  • Redis: a shared, distributed cache.
  • Hazelcast / Infinispan: distributed in-memory data grids.
  • JCache (JSR-107) providers such as Ehcache 3.
  • A plain ConcurrentHashMap fallback, with no expiry, suitable for development only.

Key points to cover:

  • Local vs distributed: local caches are the fastest, but each instance holds its own copy, and they go stale independently. Distributed caches are shared, but add a network hop. Two-level designs combine both.
  • The HTTP caching layer (ETags, Cache-Control, CDNs) is separate, and often even more effective.

Learn it in depth → Caching Strategies

Q2. How would you implement caching in a Spring Boot application?

Short answer:

  1. Add spring-boot-starter-cache plus a provider (Caffeine or Redis).
  2. Add @EnableCaching.
  3. Annotate read methods with @Cacheable.
  4. Keep the cache correct with @CacheEvict/@CachePut on writes, plus a TTL as a safety net.
  5. Configure sizes and TTLs per cache.
@Service
class ProductService {
    @Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
    public ProductDto find(long id) { return mapper.toDto(repo.findById(id).orElse(null)); }

    @CacheEvict(cacheNames = "products", key = "#id")
    @Transactional
    public void updatePrice(long id, BigDecimal price) { repo.findById(id).orElseThrow().setPrice(price); }
}
spring:
  cache:
    type: redis
    redis:
      time-to-live: 10m
      cache-null-values: false

Common trap: caching mutable entities, or JPA proxies, instead of immutable DTOs. And calling a @Cacheable method from the same class, which bypasses the proxy, so there's no caching.

Q3. How does Spring Boot simplify the data-access layer?

Short answer:

  • Auto-configuration: the DataSource with a HikariCP pool, EntityManagerFactory, transaction manager and JPA settings, all from spring.datasource.* and spring.jpa.*.
  • Spring Data repositories: CRUD, paging, derived queries (findByStatusAndCreatedAtAfter), @Query, projections and specifications, with no implementation code.
  • Exception translation into DataAccessException.
  • Schema management: Flyway or Liquibase run automatically at startup.
  • Test slices: @DataJpaTest, with Testcontainers.

Key points to cover:

  • The trade-off is hidden SQL. Always check the generated queries (org.hibernate.SQL=DEBUG), and watch for N+1 problems.

Learn it in depth → N+1 Query Problem

Q4. What are the best practices for managing transactions in Spring Boot?

Short answer:

  • Put @Transactional on service-layer methods (the business unit of work), not on controllers or repositories.
  • Keep transactions short. No remote calls, message sends or file I/O inside them. Use the outbox pattern for events that must be consistent with the database change.
  • Use readOnly = true on queries.
  • Know that checked exceptions don't roll back by default (rollbackFor).
  • Avoid self-invocation.
  • Choose propagation deliberately: REQUIRES_NEW for audit logs that must persist even when the main transaction fails.
  • Set timeouts.
  • Use optimistic locking (@Version) for concurrent edits.
  • Disable Open Session in View (spring.jpa.open-in-view=false).
@Transactional(readOnly = true)
public OrderView view(long id) { … }

@Transactional(timeout = 5, rollbackFor = PaymentDeclinedException.class)
public Order checkout(Cart cart) throws PaymentDeclinedException { … }

Learn it in depth → @Transactional Deep Dive

Q5. What's the difference between cache eviction and cache expiration?

Short answer: Eviction removes entries to respect a capacity limit, chosen by a policy (LRU, LFU, or W-TinyLFU in Caffeine), and is triggered by space pressure. Expiration removes entries because they're too old, based on time (TTL after write, or time-to-idle after the last access), and it bounds staleness.

Key points to cover:

  • In Spring, "@CacheEvict" means explicit invalidation, triggered by your code when the data changes. That's a third mechanism, and the one that actually keeps a cache correct.
  • Use all three: size limits (eviction), TTL (expiration), and explicit invalidation on writes.

Q6. How do you implement pagination in a Spring Boot application?

Short answer: Accept a Pageable (?page=0&size=20&sort=createdAt,desc), pass it to a Spring Data method, and return the content plus page metadata.

public interface OrderRepository extends JpaRepository<Order, Long> {
    Page<Order> findByCustomerId(long customerId, Pageable pageable);                 // content + total count
    Slice<Order> findByStatus(OrderStatus status, Pageable pageable);                   // no count query
    @Query("select o from Order o where o.id < :cursor order by o.id desc")
    List<Order> nextPage(@Param("cursor") long cursor, Limit limit);                    // keyset (Spring Data 3.2+)
}

@GetMapping("/orders")
PagedModel<OrderDto> list(@RequestParam long customerId,
                          @PageableDefault(size = 20, sort = "createdAt", direction = DESC) Pageable pageable) {
    return new PagedModel<>(repo.findByCustomerId(customerId, pageable).map(mapper::toDto));
}

Key points to cover:

  • Page runs an extra COUNT query. Use Slice when you only need "has next page".
  • Offset pagination gets slow on deep pages, because the database still scans and discards all the skipped rows. For feeds or infinite scroll, use keyset (cursor) pagination (WHERE id < :lastSeen), or Spring Data's ScrollPosition.
  • Cap size (spring.data.web.pageable.max-page-size), so clients can't request a million rows.

Q7. How would you implement soft delete for audit purposes?

Short answer: Add a deleted flag, or better, a deleted_at timestamp. Intercept deletes, so they become updates, and filter deleted rows out of every query:

@Entity
@SQLDelete(sql = "UPDATE customer SET deleted_at = now() WHERE id = ? AND version = ?")   // repo.delete() → UPDATE
@SQLRestriction("deleted_at IS NULL")                                                     // Hibernate 6.3+ (replaces @Where)
public class Customer {
    @Id Long id;
    @Version Long version;
    Instant deletedAt;
}

Key points to cover:

  • Hibernate 6.4+ has a built-in @SoftDelete annotation.
  • Unique constraints break when a deleted row still holds the email. Use a partial or filtered index (WHERE deleted_at IS NULL, in PostgreSQL), or include deleted_at in the unique key.
  • Cascades and relationships: decide what happens to children.
  • Regulations such as GDPR may require real deletion or anonymisation of personal data, so soft delete isn't always compliant.
  • Pair it with Envers or an audit table, if you need to know who deleted what, and when.

Q8. Scenario: design a REST API for managing user data. How do you structure the application?

Short answer: A layered, feature-oriented structure:

  • Controller (UserController): HTTP mapping, request and response DTOs, @Valid validation, status codes (201 with Location, 204, 404). No business logic.
  • Service (UserService): business rules (a unique email, password hashing), transaction boundaries, and domain events (UserRegistered).
  • Repository (UserRepository extends JpaRepository): persistence only.
  • Mapper (MapStruct): entity ↔ DTO conversion.
  • Cross-cutting concerns: a @RestControllerAdvice returning Problem Details, Spring Security (a user may only read or update themselves, while admins can manage everyone), pagination for listing, and OpenAPI documentation.
com.shop.user
 ├── api/        UserController, CreateUserRequest, UserResponse
 ├── domain/     User, UserService, UserRegistered
 ├── persistence/UserRepository
 └── config/     SecurityConfig

Key points to cover:

  • Never expose entities or password hashes in responses.
  • Use PATCH for partial updates, and idempotent PUT/DELETE.
  • Test each layer: @WebMvcTest, unit tests, and @DataJpaTest.

Follow-up questions this topic invites — and their answers

Q: What is a cache stampede, and how do you prevent it? A: Many requests miss the same expired key at once, and all hit the database. Mitigations: @Cacheable(sync = true) (one loader per key per instance), early or background refresh (Caffeine refreshAfterWrite), random TTL jitter, and request coalescing.

Q: @CachePut vs @CacheEvict on update? A: @CachePut always runs the method, and stores its return value, which keeps the cache warm. @CacheEvict removes the entry, so the next read reloads it. Eviction is safer when the updated value isn't what the read method would return.

Q: How do you batch inserts efficiently with JPA? A: Set spring.jpa.properties.hibernate.jdbc.batch_size (for example 50), plus order_inserts/order_updates. Avoid IDENTITY ID generation, which disables insert batching, in favour of sequences. Flush and clear the persistence context periodically for very large batches.

Q: Why use DTO projections for read endpoints? A: They select only the needed columns, avoid lazy-loading and N+1 surprises, bypass dirty checking, and decouple the API from the entity model.

Previous

Spring Boot Configuration, Profiles & Secrets — Interview Questions

Next

Spring Boot Testing, Error Pages & Deployment — Interview Questions

AI Tutor

Lesson: Spring Boot Data, Transactions & Caching — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.