3

When a method is created under a specific rule of Spring Data JPA, a method that calls the corresponding query is created.

For example,

public interface CustomerJpaRepository implements JpaRepository<Customer, Long>{

    public List<Customer> findByName(String name);
}

findByName() generate the query similar to one below.

select * from Customer where name = name;

I am curious about this principle. To be precise, I'm curious about the code that parses this method and turns it into a query.

I looked at the code of the SimpleJpaRepository class that implements JpaRepository, but could not find a clue. (Of course, there is a possibility that I did not find it).

In summary, when a method consisting of specific words is declared in JpaRepository, I am curious about the code that actually executes this method internally. More specifically, I'd like to see the code that makes this method works.

If there is no code to do this internally (I personally doubt it's possible...), I want to know how it is implemented in detail, if there is a link or material that explains the principle or internal process, please share related references.

doljae
  • 39
  • 4

2 Answers2

5

The parsing logic for creating queries from spring-data repository method names is currently mainly declared in the package org.springframework.data.repository.query.parser.

Basically, a repository method name string is parsed into a PartTree, which contains Parts representing defined abstract query criteria.

The PartTree can then be used to create a more specific query object, e.g. with a JpaQueryCreator, or a RedisQueryCreator, depending on the type of repository.

fladdimir
  • 1,230
  • 1
  • 5
  • 12
-1

I recommend you to check this Query Creation spring doc It explains the rules of how the method convert into a query.

Bhushan
  • 104
  • 1
  • 9
  • Thanks. Actually I already read this article, What I'm looking for is the code that makes the query method work. – doljae Dec 22 '21 at 15:15
  • The docs only show us how to use it, but NOT show us how it is implemented behind the scene – Tạ Anh Tú Jul 06 '23 at 07:57
  • I think that Spring will use reflection to create queries based on the method name at run time, here is a reference: https://www.linkedin.com/pulse/java-reflection-api-how-spring-uses-shivangam-soni/ – Tạ Anh Tú Jul 06 '23 at 08:08