Spring Data
Nested Object
Query Methods
Property Access
Java Development

Spring data, find by property of a nested object

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Spring Data JPA can derive repository queries from nested entity properties, which is often the cleanest solution for simple lookups. Instead of writing JPQL immediately, you can describe the property path in the repository method name. This works well when the path is short and the query intent stays obvious.

Derived Query Names Follow Entity Properties

The method name must refer to Java entity property names, not database column names. For example, if an order has a customer field and Customer has an email field, the repository can query that nested path directly.

java
1import jakarta.persistence.Entity;
2import jakarta.persistence.GeneratedValue;
3import jakarta.persistence.GenerationType;
4import jakarta.persistence.Id;
5import jakarta.persistence.ManyToOne;
6
7@Entity
8public class Customer {
9    @Id
10    @GeneratedValue(strategy = GenerationType.IDENTITY)
11    private Long id;
12
13    private String email;
14
15    public String getEmail() {
16        return email;
17    }
18
19    public void setEmail(String email) {
20        this.email = email;
21    }
22}
23
24@Entity
25public class PurchaseOrder {
26    @Id
27    @GeneratedValue(strategy = GenerationType.IDENTITY)
28    private Long id;
29
30    @ManyToOne
31    private Customer customer;
32
33    public Customer getCustomer() {
34        return customer;
35    }
36
37    public void setCustomer(Customer customer) {
38        this.customer = customer;
39    }
40}

The repository method can then be written like this:

java
1import java.util.List;
2import org.springframework.data.jpa.repository.JpaRepository;
3
4public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, Long> {
5    List<PurchaseOrder> findByCustomerEmail(String email);
6}

Spring interprets CustomerEmail as the path customer.email.

Use Underscores When the Path Needs Clarification

Spring can often parse nested paths without separators, but underscores make ambiguous cases easier to read.

java
List<PurchaseOrder> findByCustomer_Email(String email);

Both forms are commonly seen. The underscore version becomes especially helpful when property names can be parsed in more than one way or when the method name is already long.

Add More Conditions Carefully

You can combine nested-property filters with other derived-query keywords.

java
List<PurchaseOrder> findByCustomerEmailAndStatus(String email, String status);

This is convenient for ordinary queries, but method names can become unreadable if you keep adding conditions, sorting, ranges, and null checks. Once the method name starts feeling like a sentence parser, the design has crossed the line where explicit JPQL or specifications are usually better.

Use JPQL When Semantics Need More Control

Derived queries are great until the query needs custom join behavior, null logic, or fetch strategy.

java
1import java.util.List;
2import org.springframework.data.jpa.repository.Query;
3import org.springframework.data.repository.query.Param;
4
5public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, Long> {
6    @Query("""
7        select o
8        from PurchaseOrder o
9        join o.customer c
10        where c.email = :email
11    """)
12    List<PurchaseOrder> findByCustomerEmailExplicit(@Param("email") String email);
13}

An explicit query is not a failure. It is the right tool when the derived method name stops being the clearest representation of the actual query.

Watch for Fetching and Performance Issues

A method name can be correct and still perform badly. If later code serializes or maps nested associations, lazy loading can trigger extra queries. In read-heavy paths, a fetch join or a projection may be more appropriate than a simple derived method.

Repository design should be driven by both correctness and the data access pattern. A neat method name does not guarantee efficient SQL.

Integration Tests Matter Here

Repository tests are worth the cost for nested-property queries because they confirm both parsing and actual database behavior.

java
1import static org.assertj.core.api.Assertions.assertThat;
2import java.util.List;
3import org.junit.jupiter.api.Test;
4import org.springframework.beans.factory.annotation.Autowired;
5import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
6
7@DataJpaTest
8class PurchaseOrderRepositoryTest {
9    @Autowired
10    private PurchaseOrderRepository repository;
11
12    @Test
13    void loadsOrdersByNestedCustomerEmail() {
14        List<PurchaseOrder> results = repository.findByCustomerEmail("[email protected]");
15        assertThat(results).isNotNull();
16    }
17}

Mock-only tests cannot prove that Spring parsed the path the way you intended.

Common Pitfalls

  • Writing repository method paths from database column names instead of Java property names.
  • Letting derived method names grow so long that the query intent becomes unclear.
  • Assuming nested-property queries automatically solve lazy-loading or fetch-performance issues.
  • Skipping explicit JPQL when the query needs custom join or null-handling semantics.
  • Relying only on mocks instead of integration tests for repository behavior.

Summary

  • Spring Data can derive queries from nested entity properties such as customer.email.
  • Repository method names must follow Java property paths, not database column names.
  • Underscores can improve readability for nested paths.
  • Derived queries work best for short, clear lookups.
  • Switch to JPQL or specifications when the query logic or performance needs more control.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.