Spring Data JPA Projections Interview Questions and Answers

Master Spring Data JPA Projections with interview questions covering interface projections, DTO projections, dynamic projections, closed vs open projections, nested projections, and production best practices.


Introduction

In enterprise applications, it is often unnecessary and inefficient to fetch an entire entity from the database.

For example, a Customer entity may contain:

  • Customer ID
  • Name
  • Email
  • Phone
  • Address
  • Date of Birth
  • KYC Details
  • Account Balance
  • Audit Fields

If a customer listing page only displays ID, Name, and Email, loading all columns wastes:

  • Memory
  • Network bandwidth
  • Database resources

Spring Data JPA solves this problem using Projections, which fetch only the required columns.


Projection Architecture

flowchart LR

Application --> Repository

Repository --> Projection

Projection --> Hibernate

Hibernate --> Database

Q1. What are Projections?

Answer

Projections allow Spring Data JPA to retrieve only selected fields instead of loading the complete entity.

Benefits

  • Reduced memory usage
  • Faster queries
  • Smaller network payload
  • Better application performance

Instead of returning

Customer Entity

Return

Customer Name

Email

Q2. Why should we use Projections?

Without Projection

SELECT *

FROM CUSTOMER

With Projection

SELECT

NAME,

EMAIL

FROM CUSTOMER

Only the required columns are retrieved.

Data Retrieval

flowchart LR

Database --> SelectedColumns

SelectedColumns --> Projection

Projection --> Application

Q3. What is Interface Projection?

Spring automatically implements projection interfaces.

Example

public interface

CustomerView{

    String getName();

    String getEmail();

}

Repository

List<CustomerView>

findByCity(

String city);

Spring generates the implementation dynamically.


Q4. What is DTO Projection?

DTO Projection creates custom objects.

Example

public record

CustomerDTO(

Long id,

String name){ }

Repository

@Query(

"""

SELECT new

com.bank.dto.CustomerDTO(

c.id,

c.name)

FROM Customer c

""")

Advantages

  • Type-safe
  • Immutable (using records)
  • Better API design

Q5. What is Dynamic Projection?

Dynamic Projection allows the caller to decide the projection type.

Example

<T>

List<T>

findByCity(

String city,

Class<T> type);

Usage

repository.findByCity(

"Dallas",

CustomerDTO.class);

The same repository method can return different projections.


Q6. What are Closed and Open Projections?

Closed Projection

Only mapped fields.

String getName();

Open Projection

Uses SpEL expressions.

@Value(

"#{target.firstName +

' ' +

target.lastName}")

String getFullName();

Comparison

Closed Open
Faster Slightly slower
Direct mapping Expression evaluation
Recommended Use only when needed

Q7. What are Nested Projections?

Nested Projections retrieve related entities.

Example

interface EmployeeView{

    DepartmentView

    getDepartment();

}

Nested Projection

flowchart LR

EmployeeProjection --> DepartmentProjection

DepartmentProjection --> DepartmentName

Useful for parent-child relationships.


Q8. When should DTO Projection be preferred?

DTO Projection is ideal when

  • Returning REST responses
  • Reducing network traffic
  • Avoiding LazyInitializationException
  • Preventing unnecessary entity loading

Most enterprise REST APIs return DTOs instead of entities.


Q9. Projections vs Entity Loading

Projection Entity
Partial columns All columns
Faster Slower
Lower memory Higher memory
Read-only Read & Update
API friendly Persistence model

Choose projections for read operations whenever full entity state is not required.


Q10. Projection Best Practices

Prefer Interface Projection

For simple read-only queries.


Prefer DTO Projection

For REST APIs.


Use Records

For immutable DTOs (Java 16+).


Avoid Open Projections

Unless computed fields are necessary.


Never Return Entities Directly

From public REST APIs.


Banking Example

flowchart TD

CustomerRepository --> CustomerProjection

CustomerProjection --> Hibernate

Hibernate --> PostgreSQL

CustomerProjection --> CustomerAPI

Only customer summary information is returned.


Common Interview Questions

  • What are Projections?
  • Why use Projections?
  • Interface Projection?
  • DTO Projection?
  • Dynamic Projection?
  • Closed vs Open Projection?
  • Nested Projection?
  • Projection vs Entity?
  • DTO vs Entity?
  • Projection best practices?

Quick Revision

Topic Summary
Projection Partial entity retrieval
Interface Projection Auto-generated interface
DTO Projection Constructor-based DTO
Dynamic Projection Runtime projection type
Closed Projection Direct field mapping
Open Projection Uses SpEL
Nested Projection Related entity projection
Record DTO Immutable projection
Entity Full object loading
Projection Optimized read queries

Projection Execution Flow

sequenceDiagram
Application->>Repository: findByCity()
Repository->>Hibernate: Generate SELECT
Hibernate->>Database: Required Columns
Database-->>Hibernate: Partial Data
Hibernate-->>Projection: Map Result
Projection-->>Application: DTO / Interface

Production Example – Banking Customer Dashboard

A banking application provides a customer dashboard.

Requirements

  • Show customer ID
  • Customer name
  • Email
  • Account type
  • Current balance

The complete Customer entity contains more than 40 columns, including KYC documents, addresses, audit fields, and account metadata.

Implementation

  • Interface Projection is used for internal reporting.
  • DTO Projection (Java Record) is returned by REST APIs.
  • Nested Projection retrieves account information.
  • Dynamic Projection allows the same repository method to support different UI screens.
public record CustomerSummary(
    Long id,
    String name,
    String email,
    String accountType,
    BigDecimal balance
) {}
flowchart LR

CustomerController --> CustomerService

CustomerService --> CustomerRepository

CustomerRepository --> CustomerSummary

CustomerSummary --> Hibernate

Hibernate --> PostgreSQL

This approach reduces query execution time, minimizes network traffic, and avoids exposing unnecessary database fields through public APIs.


Key Takeaways

  • Projections retrieve only the required columns instead of loading complete entities.
  • Interface Projections are simple, lightweight, and automatically implemented by Spring Data JPA.
  • DTO Projections provide immutable, API-friendly objects and are ideal for REST responses.
  • Dynamic Projections allow a single repository method to return different projection types based on runtime requirements.
  • Closed Projections are more efficient than Open Projections, which rely on SpEL expression evaluation.
  • Nested Projections support retrieving selected fields from related entities without loading the entire object graph.
  • Prefer projections for read-heavy operations to reduce memory usage, improve query performance, and minimize network overhead.
  • In enterprise applications, return DTOs or projections from service and controller layers instead of exposing JPA entities directly.