Spring Data JPA/Boot: findBy ... or

8
我想在我的仓库中编写一个查找方法,根据一个字段或另一个字段来查找对象,同时提供一个参数,例如:
@RepositoryDefinition(domainClass = Person.class, idClass = Long.class)
public interface PersonRepository extends CrudRepository<Person, Long> {

    List<Person> findAllByIdOrAnotherId(someId);
}

我该如何在不使用SQL的情况下实现这个功能?


2
您可以将您的方法注释为 @Query("from Person p where p.id = ?1 or p.anotherId = ?1") - manish
2个回答

10

我给这个方法增加了第二个参数,然后它就正常工作了。

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

这只是一个方法的定义,因为我从服务中将同样的参数传递给该方法:

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

0

Spring Data JPA 的一个很酷的功能是你可以在接口中定义抽象方法作为自定义查询。

简而言之,你只需要指定你想要查询的 @Entity 字段名称,就可以定义一个新的搜索条件。所以,假设我想通过 IdCustomId 进行 findAll() 查询。这两个字段都是我的领域类上的字段。我会这样做:

List<Person> findAllByIdOrCustomId(someId, someCustomId);

更多信息,请查看下面的链接: Spring Data JPA - 定义查询方法


我已经尝试过了,但应用程序甚至无法启动。这是堆栈跟踪:http://pastebin.com/TLaWLAer - biniam
我受到公司防火墙的限制,目前无法打开并查看此链接。 - Mechkov
请在您有时间的时候查看此内容,并回复我。谢谢。 - biniam
根据您的异常日志,问题出现在TransactionService类中创建transactionRepository bean时。我认为您应该尝试使用setter注入而不是构造函数注入来创建transactionRepository bean。 - Naresh Joshi
这是错误的,应用程序崩溃,并显示明确的异常消息:部分CustomId SIMPLE_PROPERTY (1)没有可用参数:[Is,Equals] NEVER。换句话说,您必须提供第二个参数,不能同时使用相同的参数用于Id和CustomId。 - Melardev
@Melardev 是的,你说得对。我已经修改了我的回答。谢谢。 - Mechkov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接