All posts / Spring Boot

Spring Boot + JPA + Virtual Threads (Java 21): Avoid N+1, OSIV & Pagination Pitfalls

NordLearn · · 5 min read

Part of the series “Java 21 & Spring Boot” · part 4 of 5
  1. Immutability in Java 21: Records, Defensive Copying, and Collections
  2. Modern Spring Boot with Java 21 — Virtual Threads, ScopedValue, and Structured Concurrency
  3. Java Virtual Threads Are a Bigger Deal Than You Think
  4. Spring Boot + JPA + Virtual Threads (Java 21): Avoid N+1, OSIV & Pagination Pitfalls
  5. The Complete Guide to RestClient in Spring Boot 3.2 with Java 21 Virtual Threads
On this page

The Ultimate Production Guide (2026 Edition)

If you’re building modern backend systems with Spring Boot 3.x and Java 21, you’ve likely encountered these terms: Virtual Threads, N+1 queries, Open Session In View (OSIV), and pagination issues. But here’s the thing — understanding them individually isn’t enough. The real danger lies in how they interact.

This comprehensive guide will show you how to build production-grade Spring Boot applications that scale. We’ll cover:

  • What N+1 really means and why it matters more with virtual threads
  • Why returning entities from controllers is a production anti-pattern
  • The hidden dangers of OSIV (especially with high concurrency)
  • Why JOIN FETCH breaks pagination and what to do instead
  • Production-tested best practices for performance and scalability

Let’s dive in.

1. Virtual Threads in Spring Boot: The Game Changer

Java 21’s Project Loom introduced virtual threads, and Spring Boot 3.2+ makes them trivially easy to enable:

spring:
  threads:
    virtual:
      enabled: true

That’s it. Spring replaces the default platform thread pool with:

Executors.newVirtualThreadPerTaskExecutor()

Why This Matters

Traditional thread pools are limited by OS threads. You might run 200 concurrent requests before running out of memory or threads.

Virtual threads change the game:

  • Thousands of concurrent requests on modest hardware
  • Blocking I/O becomes cheap (JDBC, JPA, REST calls)
  • Higher throughput for I/O-heavy applications
  • Perfect for microservices and database-driven APIs

But here’s the catch: Virtual threads amplify existing problems. A latent N+1 issue that affected 200 users can now impact 5,000 concurrent users. Your database becomes the bottleneck.

2. The N+1 Problem: Why It’s Your Worst Enemy

The Classic Example

Let’s say you have this entity structure:

@Entity
public class Customer {
    @Id
    private Long id;
    private String name;

    @OneToMany(mappedBy = "customer", fetch = FetchType.LAZY)
    private List<Order> orders;
}

And this innocent-looking code:

// In your service layer
List<Customer> customers = customerRepository.findAll();

for (Customer customer : customers) {
    System.out.println(customer.getOrders().size());
}

What Actually Happens in SQL

Query 1 — Load customers:

SELECT * FROM customer;

Queries 2-N — For each customer:

SELECT * FROM orders WHERE customer_id = 1;
SELECT * FROM orders WHERE customer_id = 2;
SELECT * FROM orders WHERE customer_id = 3;
-- ... and so on

If you have 100 customers:

  • 1 initial query + 100 queries for orders
  • = 101 total queries

The Virtual Thread Multiplier Effect

With traditional threads (200 concurrent users):

  • 101 queries × 200 requests = 20,200 queries

With virtual threads (5,000 concurrent users):

  • 101 queries × 5,000 requests = 505,000 queries

🔥 Your database melts.

How to Detect N+1 in Your Logs

Enable Hibernate SQL logging:

spring:
  jpa:
    show-sql: true
    properties:
      hibernate:
        format_sql: true

Watch for repeated similar queries with different parameter values. That’s your smoking gun.

3. Never Return Entities From Controllers

This is the most violated rule in Spring Boot applications. Let me show you why it’s dangerous.

The Bad Pattern

@RestController
@RequestMapping("/api/customers")
public class CustomerController {
    
    @GetMapping
    public List<Customer> getCustomers() {
        return customerService.findAll();
    }
}

Four Critical Problems

Problem 1: LazyInitializationException

(When OSIV Disabled. Explain soon)

org.hibernate.LazyInitializationException: 

Let me explain this with a simple analogy:

Think of your database connection like a phone call:

  • When you’re on the call (transaction active) → you can ask for data
  • When you hang up (transaction ends) → you can’t ask for more data

What happens with LAZY loading:

// Step 1: Service method starts (phone call begins)
@Transactional
public Customer findCustomer(Long id) {
    Customer customer = repository.findById(id); 
    // At this point: customer.name is loaded 
    // But customer.orders is NOT loaded yet (it's lazy)
    return customer;
} // Step 2: Method ends, transaction closes (phone call hangs up)

// Step 3: Controller tries to return customer as JSON
@GetMapping("/{id}")
public Customer getCustomer(@PathVariable Long id) {
    Customer customer = service.findCustomer(id);
    return customer; 
    // JSON serializer tries: customer.getOrders()
    // ERROR! Transaction is closed, can't load orders now
}

Why it fails:

  1. @Transactional ends when service method returns
  2. Database connection is closed/returned to pool
  3. Controller receives the Customer object with unloaded orders
  4. Jackson (JSON serializer) tries to access customer.getOrders()
  5. Hibernate says: “Sorry, I need a database connection to load that, but the transaction is closed!”

With OSIV enabled :

  • Transaction stays open until JSON serialization completes
  • Lazy fields “magically” work in controllers
  • But this creates the connection pool problems we discussed

The right solution: Load everything you need inside the transaction, or use DTOs.

Problem 2: Hidden N+1 Query Explosions

Jackson serializer walks the object graph automatically:

// Customer has orders
// Each Order has a customer reference
// Each customer reference has orders again...

This can trigger cascading queries that explode exponentially.

Problem 3: Security Vulnerabilities

Your entity might contain sensitive fields:

@Entity
public class Customer {
    private String name;
    private String email;
    private String passwordHash;  // ⚠️ Exposed!
    private String internalNotes; // ⚠️ Exposed!
}

Returning entities exposes your entire database schema and potentially sensitive data.

Problem 4: API Coupling

Your database structure becomes your public API contract. Change a column name? You break client applications.

The Correct Approach: DTO Projections

Use Java 21 records for clean, immutable DTOs:

public record CustomerSummary(
    Long id,
    String name,
    String email,
    long orderCount,
    LocalDateTime lastOrderDate
) {}

Repository with JPQL projection:

@Query("""
    SELECT new com.example.dto.CustomerSummary(
        c.id,
        c.name,
        c.email,
        COUNT(o),
        MAX(o.orderDate)
    )
    FROM Customer c
    LEFT JOIN c.orders o
    GROUP BY c.id, c.name, c.email
    """)
Page<CustomerSummary> findCustomerSummaries(Pageable pageable);

Controller:

@GetMapping
public Page<CustomerSummary> getCustomers(Pageable pageable) {
    return customerService.findCustomerSummaries(pageable);
}

Why This is Superior

  • Single SQL query — no N+1
  • Safe pagination — works correctly with LIMIT/OFFSET
  • Controlled data exposure — only what you want to share
  • Small memory footprint — no entity graph loading
  • API stability — decouple database from API contract

4. The JOIN FETCH + Pagination Trap

Many developers try to solve N+1 with JOIN FETCH:

The Broken Approach

@Query("""
    SELECT DISTINCT c
    FROM Customer c
    JOIN FETCH c.orders
    """)
Page<Customer> findAllWithOrders(Pageable pageable);

This breaks pagination completely.

Why It Fails

When you JOIN FETCH a OneToMany relationship, SQL produces a Cartesian product:

SELECT c.*, o.*
FROM customer c
JOIN orders o ON c.id = o.customer_id
LIMIT 20;

Result set:

CustomerID | CustomerName | OrderID
--------------------------------
1          | Alice        | 101
1          | Alice        | 102
1          | Alice        | 103
2          | Bob          | 201
2          | Bob          | 202
3          | Carol        | 301
...

The LIMIT 20 applies to rows, not customers. You asked for 20 customers but might get only 3-5 actual customer entities.

Hibernate loads all data into memory and paginates there. With large datasets, this causes OutOfMemoryError.

The Correct Solutions

Option 1: DTO Projection with Aggregates

@Query("""
    SELECT new com.example.dto.CustomerWithOrderCount(
        c.id,
        c.name,
        COUNT(o)
    )
    FROM Customer c
    LEFT JOIN c.orders o
    GROUP BY c.id, c.name
    """)
Page<CustomerWithOrderCount> findCustomersWithOrderCount(Pageable pageable);

Option 2: Fetch Separately (for full order details)

// First, get customer IDs
Page<Long> customerIds = customerRepository.findAllIds(pageable);

// Then, batch fetch orders
List<Customer> customers = customerRepository.findByIdIn(customerIds.getContent());

5. Open Session In View (OSIV): The Silent Killer

By default, Spring Boot enables OSIV:

spring:
  jpa:
    open-in-view: true  # ⚠️ Default is true!

What OSIV Does

OSIV keeps the Hibernate session (and database connection) open throughout the entire HTTP request lifecycle:

Request arrives
    ↓
Transaction begins
    ↓
Service layer executes
    ↓
Transaction commits  ← Normal apps close connection here
    ↓
Controller processes result
    ↓
JSON serialization occurs  ← OSIV keeps connection open here!
    ↓
Response sent
    ↓
Connection finally released

Why This Is Dangerous

Problem 1: Connection Pool Exhaustion

With platform threads (200 max requests):

  • OSIV holds 200 connections during serialization
  • Pool size: 10–30 connections
  • Result: Connection pool exhausted quickly

With virtual threads (5,000+ concurrent requests):

  • OSIV tries to hold 5,000 connections
  • Pool size: still 10–30 connections
  • Result: Complete system failure

Problem 2: Long-Held Transactions

Database connections are precious resources. OSIV holds them during:

  • JSON serialization (complex objects)
  • Network I/O (slow client connections)
  • Additional REST calls in controller logic

This creates artificial database bottlenecks.

Problem 3: Hidden N+1 Queries

OSIV masks N+1 problems during development. Lazy collections “magically” load in the controller:

@GetMapping("/{id}")
public Customer getCustomer(@PathVariable Long id) {
    Customer customer = customerService.findById(id);
    // OSIV allows this to work (but triggers N+1):
    customer.getOrders().forEach(System.out::println);
    return customer;
}

In production with OSIV disabled, this throwsLazyInitializationException.

Disable OSIV Immediately

spring:
  jpa:
    open-in-view: false

How to Fix Your Code After Disabling OSIV

@Transactional(readOnly = true)
public Customer findById(Long id) {
    return customerRepository.findById(id)
        .orElseThrow();
}

// Controller
@GetMapping("/{id}")
public CustomerResponse getCustomer(@PathVariable Long id) {
    Customer customer = customerService.findById(id);
    // This works with OSIV, fails without it
    return new CustomerResponse(
        customer.getName(),
        customer.getOrders().size()  // ⚠️ LazyInitializationException
    );
}

Use DTO projection:

@Query("""
    SELECT new com.example.dto.CustomerResponse(
        c.name,
        SIZE(c.orders)
    )
    FROM Customer c
    WHERE c.id = :id
    """)
Optional<CustomerResponse> findCustomerResponseById(@PathVariable Long id);

Key Principles

  1. Entities never leave the service layer
  2. Transactions begin and end in service methods
  3. Controllers only handle HTTP and validation
  4. DTOs are the contract between layers

Example Implementation

// DTO
public record CustomerDetailResponse(
    Long id,
    String name,
    String email,
    List<OrderSummary> recentOrders
) {}

public record OrderSummary(
    Long id,
    BigDecimal amount,
    LocalDateTime orderDate
) {}

// Repository
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
    
    @Query("""
        SELECT c
        FROM Customer c
        LEFT JOIN FETCH c.orders o
        WHERE c.id = :id
        """)
    Optional<Customer> findByIdWithOrders(@Param("id") Long id);
}

// Service
@Service
@RequiredArgsConstructor
public class CustomerService {
    
    private final CustomerRepository customerRepository;
    
    @Transactional(readOnly = true)
    public CustomerDetailResponse findCustomerDetails(Long id) {
        Customer customer = customerRepository.findByIdWithOrders(id)
            .orElseThrow(() -> new EntityNotFoundException("Customer not found"));
        
        // Map to DTO within transaction
        List<OrderSummary> recentOrders = customer.getOrders().stream()
            .sorted(Comparator.comparing(Order::getOrderDate).reversed())
            .limit(5)
            .map(order -> new OrderSummary(
                order.getId(),
                order.getAmount(),
                order.getOrderDate()
            ))
            .toList();
        
        return new CustomerDetailResponse(
            customer.getId(),
            customer.getName(),
            customer.getEmail(),
            recentOrders
        );
    }
}

// Controller
@RestController
@RequestMapping("/api/customers")
@RequiredArgsConstructor
public class CustomerController {
    
    private final CustomerService customerService;
    
    @GetMapping("/{id}")
    public ResponseEntity<CustomerDetailResponse> getCustomer(
            @PathVariable Long id) {
        return ResponseEntity.ok(customerService.findCustomerDetails(id));
    }
}

The Mental Model

Understanding the interaction between these concepts is crucial:

┌─────────────────────────────────────────────┐
│  Virtual Threads: 5,000 concurrent requests │
└───────────────────┬─────────────────────────┘
                    │ multiplies
                    ↓
┌─────────────────────────────────────────────┐
│  N+1 Queries: 100 queries per request       │
└───────────────────┬─────────────────────────┘
                    │ creates
                    ↓
┌─────────────────────────────────────────────┐
│  Database Load: 500,000 queries/second      │
└───────────────────┬─────────────────────────┘
                    │ requires
                    ↓
┌─────────────────────────────────────────────┐
│  OSIV: Holds connections during I/O         │
└───────────────────┬─────────────────────────┘
                    │ leads to
                    ↓
┌─────────────────────────────────────────────┐
│  Connection Pool Exhaustion: System crash   │
└─────────────────────────────────────────────┘

The Key Insight:

  • Virtual threads increase concurrency (good)
  • N+1 queries increase load per request (bad)
  • OSIV increases connection hold time (bad)
  • Pagination issues cause memory problems (bad)

Combine them incorrectly → system collapse Combine them correctly → massive scalability.

Final Checklist for Production

Before deploying your Spring Boot application with virtual threads:

Configuration Checklist

#Enable virtual threads
spring:
  threads:
    virtual:
      enabled: true

#Disable OSIV
  jpa:
    open-in-view: false
    
#Configure connection pool
  datasource:
    hikari:
      maximum-pool-size: 30
      leak-detection-threshold: 60000

#Enable batch processing
    properties:
      hibernate:
        jdbc:
          batch_size: 50
        order_inserts: true

Conclusion

Spring Boot 3.x with Java 21’s virtual threads offers incredible scalability potential. But with great power comes great responsibility.

The combination of:

  • ✅ Disabled OSIV
  • ✅ DTO projections instead of entities
  • ✅ Proper pagination strategies
  • ✅ N+1 query elimination
  • ✅ Optimized connection pools

…creates a production system that can handle thousands of concurrent users efficiently.

The bottom line: Think in SQL, not just Java. Virtual threads amplify both good and bad patterns. Design your data access layer carefully, and you’ll build systems that scale beautifully.

Have questions or experiences with virtual threads in production? I’d love to hear about them in the comments!