java Spring Data JPA/Boot: findBy ... 或

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40023995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:51:56  来源:igfitidea点击:

Spring Data JPA/Boot: findBy ... or

javaspring-bootspring-dataspring-data-jpa

提问by biniam

I want to write a finder method in my repository to find an object based on one field OR another one while supplying one parameter like:

我想在我的存储库中编写一个 finder 方法来查找基于一个字段或另一个字段的对象,同时提供一个参数,例如:

@RepositoryDefinition(domainClass = Person.class, idClass = Long.class)
public interface PersonRepository extends CrudRepository<Person, Long> {

    List<Person> findAllByIdOrAnotherId(someId);
}

How can I do that without using SQL?

如何在不使用 SQL 的情况下做到这一点?

回答by biniam

I added a second parameter to the method and it worked.

我向该方法添加了第二个参数并且它起作用了。

List<Transaction> findAllByIdOrParentId(Long id, Long parentId);

This is just a definition for the method because I pass the same parameter to the method from the service as:

这只是该方法的定义,因为我将相同的参数从服务传递给该方法,如下所示:

List<Transaction> transactions = transactionRepository.findAllByIdOrParentId(transactionId, transactionId);

回答by Mechkov

One of the cool things about Spring Data JPA is the fact you can define custom queries as abstract methods in your interface.

Spring Data JPA 的一项很酷的事情是您可以将自定义查询定义为接口中的抽象方法。

In a nutshell, you can define a new search criteria just by specifying the @Entityfield name you want to query by. So, let's say i want to findAll()by Idand CustomId. Both Idand CustomIdare fields on my domain class. I would do:

简而言之,您只需指定@Entity要查询的字段名称即可定义新的搜索条件。所以,假设我想findAll()通过IdCustomId。双方IdCustomId都在我的领域类的字段。我会做:

List<Person> findAllByIdOrCustomId(someId, someCustomId);

For more info, research the link below: Spring Data JPA - DEFINE QUERY METHODS

有关更多信息,请研究以下链接: Spring Data JPA - DEFINE QUERY METHODS