Back to Proxy, @Transactional Pitfalls & Internals
Q3Question 3 of 3

How does Spring Data create repository implementations

Answer: Spring Data JPA creates a JDK dynamic proxy for each repository interface at startup, delegating standard CRUD calls to SimpleJpaRepository and generating JPQL from derived method names, so you never write implementation code.

Key Concepts
  • Spring Data JPA generates repository implementations at runtime using JDK dynamic proxies, so you never write DAO boilerplate.
  • Every repository interface extends JpaRepository, CrudRepository, or Repository, and Spring scans for them during application startup.
  • SimpleJpaRepository is the concrete class that provides default implementations for save, findById, findAll, delete, and flush.
  • Derived query methods like findByAccountIdAndStatus let Spring generate JPQL from the method name, validated at startup.
  • The @Query annotation lets you write JPQL or native SQL directly on a repository method when derived queries become unreadable.
  • Custom repository interfaces let you add your own implementation methods alongside the generated ones without losing any Spring Data features.
  • At the proxy level, Spring intercepts each method call, routes it to the correct query strategy, and returns the result through the EntityManager.

Definition

Spring Data JPA creates a JDK dynamic proxy for each repository interface at startup, delegating standard CRUD calls to SimpleJpaRepository and generating JPQL from derived method names, so you never write implementation code.
  • JpaRepository is the main interface you extend in your code; it provides save, findById, findAll, deleteById, flush, and pagination methods out of the box.
  • SimpleJpaRepository is the concrete class behind every repository proxy; it uses the JPA EntityManager to run the actual database operations.
  • JDK dynamic proxy is the mechanism Spring uses to create a runtime implementation of your interface; it intercepts every method call and routes it to the correct handler.
  • Derived query method is a method like findByAccountNumberAndStatus where Spring parses the name, generates a JPQL query, and validates it at startup.
  • @Query is the annotation you use to write custom JPQL or native SQL when derived naming becomes unreadable or impossible.
  • Custom repository is a pattern where you define a separate interface and implementation class, and Spring merges your code with the generated proxy.

Think of National Bank of India headquarters issuing a standard operations manual to every new branch. The manual covers deposits, withdrawals, balance inquiries, and account closures. When a branch opens, it sends a list of services it will offer (your repository interface). Headquarters reads that list, generates trained staff for every standard service (SimpleJpaRepository), and for any custom service listed by name (like findByAccountNumberAndStatus), headquarters writes a procedure just from the name. The branch never hires its own staff for standard work. If the branch needs a truly custom process, it writes only that one procedure and headquarters merges it into the team.

Understanding the Concepts

What is a Spring Data JPA repository?

A Spring Data JPA repository is a plain Java interface that extends one of Spring Data's base interfaces: Repository, CrudRepository, ListCrudRepository, or JpaRepository. You declare the entity type and its primary key type as generic parameters. Spring creates the implementation at startup, giving you methods like save, findById, findAll, and delete without writing a single line of implementation code.

The interface acts as a contract. You tell Spring what operations you need, and Spring provides the implementation.

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;

public interface AccountRepository extends JpaRepository<Account, Long> {
    // No code needed. Spring provides:
    // save, findById, findAll, deleteById, count, flush, etc.
}
TEXT
Expected output:
AccountRepository is ready at startup with these methods:
  save(Account) -> Account
  findById(Long) -> Optional<Account>
  findAll() -> List<Account>
  deleteById(Long) -> void
  count() -> long
  flush() -> void
  saveAll(Iterable) -> List<Account>
  findAllById(Iterable) -> List<Account>

How does Spring Data create implementations at runtime?

When your Spring Boot application starts, the auto-configured @EnableJpaRepositories triggers a scan for all interfaces extending Repository or its subtypes. For each interface found, Spring creates a JDK dynamic proxy. The proxy implements your interface and routes every method call through a RepositoryComposition that knows how to handle each method type.

  • The process follows these steps:
  • Spring scans for interfaces extending Repository.
  • For each interface, Spring creates a RepositoryFactorySupport (specifically JpaRepositoryFactory).
  • The factory builds a JDK dynamic proxy with an invocation handler.
  • The invocation handler maps each method to a query execution strategy.
  • The proxy is registered as a Spring bean in the application context.
JAVA
package com.bank;

import com.bank.repository.AccountRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class ProxyInspector implements CommandLineRunner {

    private final AccountRepository accountRepository;

    public ProxyInspector(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Override
    public void run(String... args) {
        System.out.println("Repository class: " + accountRepository.getClass().getName());
        System.out.println("Is JDK proxy: " +
            java.lang.reflect.Proxy.isProxyClass(accountRepository.getClass()));

        System.out.println("Implemented interfaces:");
        for (Class<?> iface : accountRepository.getClass().getInterfaces()) {
            System.out.println("  " + iface.getSimpleName());
        }
    }
}
TEXT
Expected output:
Repository class: jdk.proxy3.$Proxy108
Is JDK proxy: true
Implemented interfaces:
  AccountRepository
  TransactionalProxy
  Advised
  DecoratingProxy

What is SimpleJpaRepository?

SimpleJpaRepository is the concrete class that Spring Data JPA uses as the default implementation target for all repository proxies. When the proxy intercepts a call to save(), findById(), or findAll(), it delegates to the corresponding method in SimpleJpaRepository. That method then calls the JPA EntityManager directly: persist() for new entities, merge() for existing ones, find() for lookups, and CriteriaQuery for listings.

SimpleJpaRepository is annotated with @Transactional(readOnly = true) at the class level, and write operations like save() and delete() override this with @Transactional. This is why your repository calls are transactional by default.

JAVA
package com.bank;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class SimpleJpaRepoDemo implements CommandLineRunner {

    private final AccountRepository accountRepository;

    public SimpleJpaRepoDemo(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Override
    public void run(String... args) {
        // save() -> SimpleJpaRepository.save() -> EntityManager.persist()
        var account = new Account("SAV2001", "Priya Sharma", new BigDecimal("50000.00"));
        Account saved = accountRepository.save(account);
        System.out.println("Saved: " + saved.getAccountNumber() + ", id=" + saved.getId());

        // findById() -> SimpleJpaRepository.findById() -> EntityManager.find()
        var found = accountRepository.findById(saved.getId());
        System.out.println("Found: " + found.map(Account::getAccountNumber).orElse("not found"));

        // count() -> SimpleJpaRepository.count() -> CriteriaQuery
        long count = accountRepository.count();
        System.out.println("Total accounts: " + count);

        // deleteById() -> SimpleJpaRepository.deleteById() -> EntityManager.remove()
        accountRepository.deleteById(saved.getId());
        System.out.println("Deleted, new count: " + accountRepository.count());
    }
}
TEXT
Expected output:
Saved: SAV2001, id=1
Found: SAV2001
Total accounts: 1
Deleted, new count: 0

How does Spring generate SQL from method names (derived queries)?

Derived query methods let you define a method on your repository interface whose name follows a naming convention, and Spring parses the name to generate JPQL at startup. The method name starts with findBy, countBy, deleteBy, or existsBy, followed by entity property names combined with keywords like And, Or, Between, LessThan, Like, OrderBy.

Spring validates derived queries at startup. If you mistype a property name (findByAccontNumber instead of findByAccountNumber), the application fails to start with a clear error message.

KeywordMethod nameGenerated JPQL
AndfindByNameAndStatusWHERE a.name = ?1 AND a.status = ?2
OrfindByNameOrStatusWHERE a.name = ?1 OR a.status = ?2
BetweenfindByBalanceBetweenWHERE a.balance BETWEEN ?1 AND ?2
LessThanfindByBalanceLessThanWHERE a.balance < ?1
GreaterThanfindByBalanceGreaterThanWHERE a.balance > ?1
LikefindByNameLikeWHERE a.name LIKE ?1
OrderByfindByStatusOrderByNameAscWHERE a.status = ?1 ORDER BY a.name ASC
Top/FirstfindTop5ByStatusWHERE a.status = ?1 LIMIT 5
JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

public interface AccountRepository extends JpaRepository<Account, Long> {

    Optional<Account> findByAccountNumber(String accountNumber);

    List<Account> findByStatus(String status);

    List<Account> findByHolderNameAndStatus(String holderName, String status);

    List<Account> findByBalanceGreaterThan(BigDecimal threshold);

    List<Account> findByBalanceBetween(BigDecimal min, BigDecimal max);

    List<Account> findTop3ByStatusOrderByBalanceDesc(String status);

    long countByStatus(String status);

    boolean existsByAccountNumber(String accountNumber);
}
JAVA
package com.bank;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class DerivedQueryDemo implements CommandLineRunner {

    private final AccountRepository accountRepository;

    public DerivedQueryDemo(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Override
    public void run(String... args) {
        accountRepository.save(new Account("SAV2001", "Priya Sharma", new BigDecimal("50000.00"), "ACTIVE"));
        accountRepository.save(new Account("SAV2002", "Rajesh Kumar", new BigDecimal("150000.00"), "ACTIVE"));
        accountRepository.save(new Account("CUR3001", "Priya Sharma", new BigDecimal("300000.00"), "ACTIVE"));
        accountRepository.save(new Account("SAV2003", "Amit Patel", new BigDecimal("5000.00"), "CLOSED"));

        System.out.println("findByAccountNumber('SAV2001'): " +
            accountRepository.findByAccountNumber("SAV2001")
                .map(Account::getHolderName).orElse("not found"));

        System.out.println("findByStatus('ACTIVE'): " +
            accountRepository.findByStatus("ACTIVE").size() + " accounts");

        System.out.println("findByBalanceGreaterThan(100000): " +
            accountRepository.findByBalanceGreaterThan(new BigDecimal("100000")).size() + " accounts");

        System.out.println("countByStatus('CLOSED'): " +
            accountRepository.countByStatus("CLOSED"));

        System.out.println("existsByAccountNumber('SAV2001'): " +
            accountRepository.existsByAccountNumber("SAV2001"));

        var top3 = accountRepository.findTop3ByStatusOrderByBalanceDesc("ACTIVE");
        System.out.println("Top 3 active by balance:");
        top3.forEach(a -> System.out.println("  " + a.getAccountNumber() + ": " + a.getBalance()));
    }
}
TEXT
Expected output:
findByAccountNumber('SAV2001'): Priya Sharma
findByStatus('ACTIVE'): 3 accounts
findByBalanceGreaterThan(100000): 2 accounts
countByStatus('CLOSED'): 1
existsByAccountNumber('SAV2001'): true
Top 3 active by balance:
  CUR3001: 300000.00
  SAV2002: 150000.00
  SAV2001: 50000.00

What is @Query for custom JPQL and native SQL?

When derived query method names become too long or when you need joins, subqueries, or aggregations, the @Query annotation lets you write JPQL or native SQL directly on the method. JPQL queries work with entity names and field names. Native queries work with table and column names.

You can also use @Modifying with @Query for UPDATE and DELETE operations. These require a @Transactional context.

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.math.BigDecimal;
import java.util.List;

public interface AccountRepository extends JpaRepository<Account, Long> {

    // JPQL query using entity field names
    @Query("SELECT a FROM Account a WHERE a.status = :status AND a.balance > :minBalance")
    List<Account> findActiveHighValueAccounts(
        @Param("status") String status,
        @Param("minBalance") BigDecimal minBalance);

    // Native SQL query using table and column names
    @Query(value = "SELECT * FROM accounts WHERE status = ?1 ORDER BY balance DESC LIMIT ?2",
           nativeQuery = true)
    List<Account> findTopAccountsByStatus(String status, int limit);

    // Projection: return only specific fields using a record
    @Query("SELECT new com.bank.dto.AccountSummary(a.accountNumber, a.balance) FROM Account a WHERE a.status = 'ACTIVE'")
    List<com.bank.dto.AccountSummary> findActiveAccountSummaries();

    // Modifying query for bulk update
    @Modifying
    @Query("UPDATE Account a SET a.status = 'FROZEN' WHERE a.balance < :threshold")
    int freezeLowBalanceAccounts(@Param("threshold") BigDecimal threshold);
}
JAVA
package com.bank.dto;

import java.math.BigDecimal;

// Java 25 record for projection
public record AccountSummary(String accountNumber, BigDecimal balance) {}
JAVA
package com.bank;

import com.bank.repository.AccountRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Component
public class CustomQueryDemo implements CommandLineRunner {

    private final AccountRepository accountRepository;

    public CustomQueryDemo(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Override
    @Transactional
    public void run(String... args) {
        var highValue = accountRepository.findActiveHighValueAccounts(
            "ACTIVE", new BigDecimal("100000"));
        System.out.println("High-value active accounts: " + highValue.size());

        var summaries = accountRepository.findActiveAccountSummaries();
        System.out.println("Active summaries:");
        summaries.forEach(s -> System.out.println("  " + s.accountNumber() + ": " + s.balance()));

        int frozen = accountRepository.freezeLowBalanceAccounts(new BigDecimal("10000"));
        System.out.println("Accounts frozen: " + frozen);
    }
}
TEXT
Expected output:
High-value active accounts: 2
Active summaries:
  SAV2001: 50000.00
  SAV2002: 150000.00
  CUR3001: 300000.00
Accounts frozen: 1

How do you write a custom repository implementation?

When you need logic that cannot be expressed as a derived query or @Query (for example, dynamic queries based on multiple optional filters), you create a custom repository implementation. The pattern uses three parts: a custom interface, an implementation class, and your main repository extending both JpaRepository and the custom interface.

The implementation class must follow the naming convention: the main repository name plus "Impl" suffix. For AccountRepository, the implementation class must be named AccountRepositoryImpl.

JAVA
package com.bank.repository;

import com.bank.model.Account;
import java.math.BigDecimal;
import java.util.List;

public interface AccountRepositoryCustom {
    List<Account> searchAccounts(String holderName, String status, BigDecimal minBalance);
}
JAVA
package com.bank.repository;

import com.bank.model.Account;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class AccountRepositoryImpl implements AccountRepositoryCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<Account> searchAccounts(String holderName, String status, BigDecimal minBalance) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Account> query = cb.createQuery(Account.class);
        Root<Account> root = query.from(Account.class);

        var predicates = new ArrayList<Predicate>();

        if (holderName != null) {
            predicates.add(cb.like(cb.lower(root.get("holderName")),
                "%" + holderName.toLowerCase() + "%"));
        }
        if (status != null) {
            predicates.add(cb.equal(root.get("status"), status));
        }
        if (minBalance != null) {
            predicates.add(cb.greaterThan(root.get("balance"), minBalance));
        }

        query.where(predicates.toArray(new Predicate[0]));
        return entityManager.createQuery(query).getResultList();
    }
}
JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;

public interface AccountRepository extends JpaRepository<Account, Long>, AccountRepositoryCustom {
    // Inherits: save, findById, findAll from JpaRepository
    // Inherits: searchAccounts from AccountRepositoryCustom
}
JAVA
package com.bank;

import com.bank.repository.AccountRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class CustomRepoDemo implements CommandLineRunner {

    private final AccountRepository accountRepository;

    public CustomRepoDemo(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Override
    public void run(String... args) {
        var results = accountRepository.searchAccounts("priya", "ACTIVE", new BigDecimal("10000"));
        System.out.println("Search results for 'priya', ACTIVE, > 10000:");
        results.forEach(a -> System.out.println("  " + a.getAccountNumber() + ": " + a.getBalance()));

        var allActive = accountRepository.searchAccounts(null, "ACTIVE", null);
        System.out.println("All active accounts: " + allActive.size());
    }
}
TEXT
Expected output:
Search results for 'priya', ACTIVE, > 10000:
  SAV2001: 50000.00
  CUR3001: 300000.00
All active accounts: 3

What is the difference between Repository, CrudRepository, and JpaRepository?

Spring Data provides a hierarchy of repository interfaces. Each level adds more methods.

InterfaceMethods providedUse when
RepositoryNone (marker only)You want full control, expose only your own methods
CrudRepositorysave, findById, findAll, delete, count, existsByIdYou need basic CRUD without pagination
ListCrudRepositorySame as CrudRepository but returns List instead of IterableYou prefer List over Iterable
PagingAndSortingRepositoryfindAll(Sort), findAll(Pageable)You need sorting and pagination
JpaRepositoryflush, saveAndFlush, deleteInBatch, findAll(Example)You need JPA-specific operations

JpaRepository extends ListCrudRepository and ListPagingAndSortingRepository, so it includes everything.

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.repository.Repository;

import java.util.Optional;

// Minimal: only exposes the methods you declare
public interface MinimalAccountRepository extends Repository<Account, Long> {
    Optional<Account> findByAccountNumber(String accountNumber);
    Account save(Account account);
    // findAll, delete, count are NOT available
}
JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.repository.CrudRepository;

// Mid-level: basic CRUD
public interface CrudAccountRepository extends CrudRepository<Account, Long> {
    // save, findById, findAll (Iterable), delete, count, existsById
}
JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;

// Full: everything including JPA-specific operations
public interface FullAccountRepository extends JpaRepository<Account, Long> {
    // All of CrudRepository + List returns + pagination + flush + batch delete
}
JAVA
package com.bank;

import com.bank.model.Account;
import com.bank.repository.FullAccountRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
public class RepositoryHierarchyDemo implements CommandLineRunner {

    private final FullAccountRepository repository;

    public RepositoryHierarchyDemo(FullAccountRepository repository) {
        this.repository = repository;
    }

    @Override
    public void run(String... args) {
        repository.save(new Account("SAV2001", "Priya Sharma", new BigDecimal("50000"), "ACTIVE"));
        repository.save(new Account("SAV2002", "Rajesh Kumar", new BigDecimal("150000"), "ACTIVE"));
        repository.save(new Account("CUR3001", "Amit Patel", new BigDecimal("300000"), "ACTIVE"));

        // JpaRepository: findAll returns List (not Iterable)
        List<Account> all = repository.findAll();
        System.out.println("findAll returns List: " + all.getClass().getSimpleName());

        // JpaRepository: pagination
        Page<Account> page = repository.findAll(PageRequest.of(0, 2, Sort.by("balance").descending()));
        System.out.println("Page 0, size 2:");
        page.forEach(a -> System.out.println("  " + a.getAccountNumber() + ": " + a.getBalance()));
        System.out.println("Total pages: " + page.getTotalPages());

        // JpaRepository: flush
        repository.flush();
        System.out.println("Flushed pending changes to database");
    }
}
TEXT
Expected output:
findAll returns List: ArrayList
Page 0, size 2:
  CUR3001: 300000
  SAV2002: 150000
Total pages: 2
Flushed pending changes to database

What is a complete banking project using Spring Data JPA?

This project manages savings accounts for National Bank of India. It uses Spring Boot 3.4, Spring Data JPA, H2 for testing, and demonstrates the repository proxy mechanism end to end.

Project structure

DIAGRAM
account-service/
├── pom.xml
└── src/
    ├── main/
    │   ├── java/
    │   │   └── com/
    │   │       └── bank/
    │   │           ├── AccountServiceApp.java
    │   │           ├── model/
    │   │           │   └── Account.java
    │   │           ├── dto/
    │   │           │   └── AccountSummary.java
    │   │           ├── repository/
    │   │           │   ├── AccountRepository.java
    │   │           │   ├── AccountRepositoryCustom.java
    │   │           │   └── AccountRepositoryImpl.java
    │   │           └── service/
    │   │               └── AccountService.java
    │   └── resources/
    │       └── application.properties
    └── test/
        └── java/
            └── com/
                └── bank/
                    └── repository/
                        └── AccountRepositoryTest.java

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><parentsyn-kw">>
        syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
        syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
        syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
    syn-kw"></parentsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>account-servicesyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
    syn-kw"></propertiessyn-kw">>

    syn-kw"><dependenciessyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-data-jpasyn-kw"></artifactIdsyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>com.h2databasesyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>h2syn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
    syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>

Account.java

JAVA
package com.bank.model;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

import java.math.BigDecimal;

@Entity
@Table(name = "accounts")
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "account_number", unique = true, nullable = false)
    private String accountNumber;

    @Column(name = "holder_name", nullable = false)
    private String holderName;

    @Column(nullable = false)
    private BigDecimal balance;

    @Column(nullable = false)
    private String status;

    protected Account() {}

    public Account(String accountNumber, String holderName, BigDecimal balance, String status) {
        this.accountNumber = accountNumber;
        this.holderName = holderName;
        this.balance = balance;
        this.status = status;
    }

    public Long getId() { return id; }
    public String getAccountNumber() { return accountNumber; }
    public String getHolderName() { return holderName; }
    public BigDecimal getBalance() { return balance; }
    public void setBalance(BigDecimal balance) { this.balance = balance; }
    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }

    @Override
    public String toString() {
        return accountNumber + " | " + holderName + " | " + balance + " | " + status;
    }
}

AccountSummary.java (Java 25 record)

JAVA
package com.bank.dto;

import java.math.BigDecimal;

public record AccountSummary(String accountNumber, BigDecimal balance) {}

AccountRepository.java

JAVA
package com.bank.repository;

import com.bank.dto.AccountSummary;
import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

public interface AccountRepository extends JpaRepository<Account, Long> {

    Optional<Account> findByAccountNumber(String accountNumber);

    List<Account> findByStatus(String status);

    List<Account> findByBalanceGreaterThan(BigDecimal threshold);

    @Query("SELECT new com.bank.dto.AccountSummary(a.accountNumber, a.balance) " +
           "FROM Account a WHERE a.status = :status")
    List<AccountSummary> findSummariesByStatus(@Param("status") String status);

    @Modifying
    @Query("UPDATE Account a SET a.status = 'FROZEN' WHERE a.balance < :threshold")
    int freezeLowBalanceAccounts(@Param("threshold") BigDecimal threshold);
}

AccountService.java

JAVA
package com.bank.service;

import com.bank.dto.AccountSummary;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class AccountService {

    private final AccountRepository accountRepository;

    public AccountService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Transactional
    public Account openAccount(String accountNumber, String holderName, BigDecimal initialDeposit) {
        var account = new Account(accountNumber, holderName, initialDeposit, "ACTIVE");
        return accountRepository.save(account);
    }

    public List<AccountSummary> getActiveAccountSummaries() {
        return accountRepository.findSummariesByStatus("ACTIVE");
    }

    public List<Account> getHighValueAccounts(BigDecimal threshold) {
        return accountRepository.findByBalanceGreaterThan(threshold);
    }

    @Transactional
    public int freezeLowBalanceAccounts(BigDecimal threshold) {
        return accountRepository.freezeLowBalanceAccounts(threshold);
    }
}

AccountRepositoryTest.java

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import java.math.BigDecimal;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

@DataJpaTest
class AccountRepositoryTest {

    @Autowired
    private AccountRepository accountRepository;

    @BeforeEach
    void setUp() {
        accountRepository.save(new Account("SAV2001", "Priya Sharma", new BigDecimal("50000"), "ACTIVE"));
        accountRepository.save(new Account("SAV2002", "Rajesh Kumar", new BigDecimal("150000"), "ACTIVE"));
        accountRepository.save(new Account("CUR3001", "Amit Patel", new BigDecimal("5000"), "CLOSED"));
    }

    @Test
    void findByAccountNumber_returnsCorrectAccount() {
        var result = accountRepository.findByAccountNumber("SAV2001");
        assertTrue(result.isPresent());
        assertEquals("Priya Sharma", result.get().getHolderName());
        System.out.println("PASS: findByAccountNumber returned " + result.get().getHolderName());
    }

    @Test
    void findByStatus_returnsActiveAccounts() {
        var active = accountRepository.findByStatus("ACTIVE");
        assertEquals(2, active.size());
        System.out.println("PASS: findByStatus returned " + active.size() + " active accounts");
    }

    @Test
    void findByBalanceGreaterThan_filtersCorrectly() {
        var highValue = accountRepository.findByBalanceGreaterThan(new BigDecimal("100000"));
        assertEquals(1, highValue.size());
        assertEquals("SAV2002", highValue.getFirst().getAccountNumber());
        System.out.println("PASS: findByBalanceGreaterThan returned " + highValue.getFirst().getAccountNumber());
    }

    @Test
    void isProxyClass() {
        boolean isProxy = java.lang.reflect.Proxy.isProxyClass(accountRepository.getClass());
        assertTrue(isProxy);
        System.out.println("PASS: AccountRepository is a JDK dynamic proxy: " + accountRepository.getClass().getName());
    }
}

How to run

BASH
cd account-service
mvn clean test
TEXT
Expected output:
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
PASS: findByAccountNumber returned Priya Sharma
PASS: findByStatus returned 2 active accounts
PASS: findByBalanceGreaterThan returned SAV2002
PASS: AccountRepository is a JDK dynamic proxy: jdk.proxy3.$Proxy108
[INFO] BUILD SUCCESS

What are common mistakes when using Spring Data repositories?

The most common mistakes involve method naming errors, missing @Modifying, and N+1 queries.

Wrong: misspelled property name in derived query

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BrokenAccountRepository extends JpaRepository<Account, Long> {

    // WRONG: "AccontNumber" is misspelled (missing 'u')
    // Spring validates at startup and the application fails to start
    Account findByAccontNumber(String accountNumber);
}
TEXT
Expected output (startup failure):
org.springframework.data.mapping.PropertyReferenceException:
  No property 'accontNumber' found for type 'Account'.
  Did you mean 'accountNumber'?

Correct: use the exact property name from the entity

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;

public interface FixedAccountRepository extends JpaRepository<Account, Long> {

    // CORRECT: matches Account.accountNumber exactly
    Account findByAccountNumber(String accountNumber);
}
TEXT
Expected output:
Application starts successfully.
findByAccountNumber("SAV2001") returns Priya Sharma's account.

Wrong: @Query UPDATE without @Modifying

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface BrokenUpdateRepository extends JpaRepository<Account, Long> {

    // WRONG: missing @Modifying annotation
    @Query("UPDATE Account a SET a.status = 'FROZEN' WHERE a.balance < :threshold")
    int freezeAccounts(java.math.BigDecimal threshold);
}
TEXT
Expected output (runtime error):
org.hibernate.hql.internal.QueryExecutionRequestException:
  Not supported for DML operations

Correct: add @Modifying and @Transactional

JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface FixedUpdateRepository extends JpaRepository<Account, Long> {

    // CORRECT: @Modifying tells Spring this is a write operation
    @Modifying
    @Query("UPDATE Account a SET a.status = 'FROZEN' WHERE a.balance < :threshold")
    int freezeAccounts(@Param("threshold") java.math.BigDecimal threshold);
}
TEXT
Expected output:
freezeAccounts(10000) returns 1 (one account frozen).

What should a senior or principal engineer know?

At the senior level, you should understand the full proxy chain: your code calls the proxy, the proxy goes through a TransactionInterceptor (if @Transactional is present), then to the query execution strategy, then to the EntityManager. Knowing this chain helps you debug issues like missing transactions, unexpected lazy loading, or slow queries.

At the principal level, you need to think about:

  • N+1 query problem: derived queries that load an entity and then trigger lazy collections in a loop generate N+1 SQL statements. Use @EntityGraph or JOIN FETCH in @Query to solve this.
  • Projection performance: returning full entities when you only need two fields wastes memory and bandwidth. Use record projections or interface projections.
  • Flush timing: SimpleJpaRepository calls flush() at specific points. Understanding when Hibernate flushes the persistence context prevents surprises with @Modifying queries that do not see uncommitted changes.
  • Custom base repository: you can replace SimpleJpaRepository with your own base class for all repositories in the application, adding audit logging or soft delete.
  • Specification pattern: for complex dynamic queries, JpaSpecificationExecutor provides a type-safe alternative to Criteria API in custom repositories.
JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface SpecAccountRepository
        extends JpaRepository<Account, Long>, JpaSpecificationExecutor<Account> {
    // Inherits: findAll(Specification), count(Specification), exists(Specification)
}
JAVA
package com.bank.repository;

import com.bank.model.Account;
import org.springframework.data.jpa.domain.Specification;

import java.math.BigDecimal;

public final class AccountSpecifications {

    private AccountSpecifications() {}

    public static Specification<Account> hasStatus(String status) {
        return (root, query, cb) -> cb.equal(root.get("status"), status);
    }

    public static Specification<Account> balanceAbove(BigDecimal threshold) {
        return (root, query, cb) -> cb.greaterThan(root.get("balance"), threshold);
    }

    public static Specification<Account> holderNameContains(String name) {
        return (root, query, cb) ->
            cb.like(cb.lower(root.get("holderName")), "%" + name.toLowerCase() + "%");
    }
}
JAVA
package com.bank;

import com.bank.repository.AccountSpecifications;
import com.bank.repository.SpecAccountRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

import static org.springframework.data.jpa.domain.Specification.where;

@Component
public class SpecificationDemo implements CommandLineRunner {

    private final SpecAccountRepository repository;

    public SpecificationDemo(SpecAccountRepository repository) {
        this.repository = repository;
    }

    @Override
    public void run(String... args) {
        var spec = where(AccountSpecifications.hasStatus("ACTIVE"))
            .and(AccountSpecifications.balanceAbove(new BigDecimal("100000")));

        var results = repository.findAll(spec);
        System.out.println("Active accounts with balance > 100000:");
        results.forEach(a -> System.out.println("  " + a.getAccountNumber() + ": " + a.getBalance()));
    }
}
TEXT
Expected output:
Active accounts with balance > 100000:
  SAV2002: 150000
  CUR3001: 300000

What are common interview follow-up questions?

  • Can you use Spring Data JPA without Spring Boot? (Yes. You annotate a configuration class with @EnableJpaRepositories and configure the EntityManagerFactory and TransactionManager beans manually.)
  • What happens if two derived query methods conflict? (Each method generates its own independent query. There is no conflict because each method has its own name and parameters.)
  • Can you use a repository without an @Entity class? (No. Spring Data JPA requires a JPA entity. For non-JPA stores, use Spring Data JDBC, Spring Data MongoDB, or Spring Data Elasticsearch.)
  • How does Spring Data handle method overloading in repositories? (It does not support overloading for derived queries. Each method name must be unique in the repository interface.)
  • Can a repository method return a Stream instead of a List? (Yes. Declare the return type as Stream and annotate with @QueryHints to enable streaming. Always close the stream in a try-with-resources block.)
  • What is the difference between @Query with JPQL and native SQL? (JPQL uses entity and field names, is portable across databases. Native SQL uses table and column names, is database-specific but supports database-specific features.)

Visual Overview

DIAGRAM
 Spring Data JPA Repository Proxy Chain
 ========================================

 ┌─────────────────────────────┐
 │ Your code calls             │
 │ accountRepository.save(acc) │
 └──────────┬──────────────────┘
            │
            ▼
 ┌──────────────────────────────┐
 │ JDK Dynamic Proxy            │
 │ (jdk.proxy3.$Proxy108)       │
 │                              │
 │ Intercepts the method call   │
 └──────────┬───────────────────┘
            │
            ▼
 ┌──────────────────────────────┐
 │ TransactionInterceptor       │
 │                              │
 │ Starts/joins a transaction   │
 │ if @Transactional is present │
 └──────────┬───────────────────┘
            │
            ▼
 ┌──────────────────────────────┐
 │ RepositoryComposition        │
 │                              │
 │ Routes the call:             │
 │  save()     -> SimpleJpaRepo │
 │  findByX()  -> DerivedQuery  │
 │  @Query     -> JPQL executor │
 │  custom()   -> YourImpl      │
 └──────────┬───────────────────┘
            │
            ▼
 ┌──────────────────────────────┐
 │ SimpleJpaRepository          │
 │                              │
 │ save()   -> em.persist()     │
 │ findById -> em.find()        │
 │ findAll  -> CriteriaQuery    │
 │ delete   -> em.remove()      │
 └──────────┬───────────────────┘
            │
            ▼
 ┌──────────────────────────────┐
 │ JPA EntityManager            │
 │ (Hibernate SessionImpl)      │
 └──────────┬───────────────────┘
            │
            ▼
 ┌──────────────────────────────┐
 │ JDBC / HikariCP              │
 │ -> Database                  │
 └──────────────────────────────┘


 Derived Query Method Name Parsing
 ==================================

  findByHolderNameAndStatus("Priya", "ACTIVE")
  │       │          │
  │       │          └── AND a.status = ?2
  │       └── WHERE a.holderName = ?1
  └── SELECT a FROM Account a

  Result: SELECT a FROM Account a
          WHERE a.holderName = ?1 AND a.status = ?2

Key Takeaway

Spring Data JPA eliminates the DAO boilerplate that every Java developer has written hundreds of times. Instead of creating a class with an EntityManager, writing save, find, update, and delete methods, and wrapping everything in transactions, you declare a plain Java interface extending JpaRepository. Spring scans for that interface at startup, creates a JDK dynamic proxy, and the proxy delegates every call to SimpleJpaRepository, which talks to the EntityManager.

The derived query mechanism is what makes Spring Data feel like magic. When you write a method named findByAccountNumberAndStatus, Spring parses the name at startup, maps each part to an entity property, and generates JPQL. If you misspell a property, the application fails to start with a clear error. For complex queries, @Query lets you write JPQL or native SQL directly on the method, and for truly dynamic queries, the custom repository pattern or JpaSpecificationExecutor gives you full Criteria API power.

In our National Bank of India account-service project, we defined an Account entity, an AccountRepository interface, and used derived queries, @Query projections with Java records, and a custom implementation with dynamic search. All of this worked through the same proxy. The test confirmed the repository bean is a JDK proxy: jdk.proxy3.$Proxy108.

At the senior level, understand the full proxy chain: your call goes through the JDK proxy, then TransactionInterceptor, then RepositoryComposition, then SimpleJpaRepository, then EntityManager, then JDBC. This chain explains why @Transactional works on repositories, why self-invocation bypasses the proxy, and where performance bottlenecks hide. At the principal level, use projections instead of full entities, apply @EntityGraph to prevent N+1 queries, and consider replacing SimpleJpaRepository with a custom base class for cross-cutting concerns like soft delete or audit logging.

Remember one sentence: Spring Data JPA turns your repository interface into a JDK dynamic proxy that routes each method call to SimpleJpaRepository for standard CRUD, to a derived JPQL query for method name conventions, or to your custom implementation for everything else.

---

Share
Use ← → arrow keys to navigate