简体   繁体   English

Spring数据JPA的查询方法如何生成查询?

[英]How query method of Spring Data JPA generate query?

When a method is created under a specific rule of Spring Data JPA, a method that calls the corresponding query is created.当在 Spring 数据 JPA 的特定规则下创建方法时,会创建调用相应查询的方法。

For example,例如,

public interface CustomerJpaRepository implements JpaRepository<Customer, Long>{

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

findByName() generate the query similar to one below. findByName() 生成类似于下面的查询。

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.我查看了实现JpaRepositorySimpleJpaRepository class 的代码,但找不到线索。 (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 .综上所述,当在 JpaRepository 中声明一个由特定单词组成的方法时,我很好奇内部实际执行该方法的代码 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.如果内部没有代码可以做到这一点(我个人怀疑是不是可以...),想知道具体是怎么实现的,如果有说明原理或内部流程的链接或资料,请分享相关参考资料.

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 .从 spring-data 存储库方法名称创建查询的解析逻辑目前主要在 package org.springframework.data.repository.query.parser中声明。

Basically, a repository method name string is parsed into a PartTree , which contains Part s representing defined abstract query criteria.基本上,存储库方法名称字符串被解析为PartTree ,其中包含表示定义的抽象查询条件的Part

The PartTree can then be used to create a more specific query object, eg with a JpaQueryCreator , or a RedisQueryCreator , depending on the type of repository.然后, PartTree可用于创建更具体的查询 object,例如使用JpaQueryCreatorRedisQueryCreator ,具体取决于存储库的类型。

I recommend you to check this Query Creation spring doc It explains the rules of how the method convert into a query.我建议您查看此查询创建spring 文档它解释了该方法如何转换为查询的规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM