从方法名称生成查询的 Spring Data 错误 [英] Spring Data error generating query from method name
问题描述
我正在尝试在我的 Spring Data JPA 存储库中实现自定义方法.
I'm trying to implement a custom method in my Spring Data JPA repository.
我正在使用从方法名称生成查询,我有这样的东西:
I'm using query generation from method name, and I have something like this:
List<Person> findByFirstNameOrLastName(String key);
我为该方法指定了一个参数,因为我有一个可以匹配 firstName
或 lastName
的搜索键,但是在应用程序启动时我得到了这个应用程序:
I specified a single parameter for the method because I have a single search key that could match firstName
or lastName
, but on application startup I'm getting this application:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'personRepository':
Invocation of init method failed; nested exception is java.util.NoSuchElementException
我想这个错误取决于方法签名...
I suppose this error depends on method signature...
那么,有没有办法使用查询创建为我的方法指定单个参数,或者我应该实现自定义逻辑来实现这一点?
So, is there a way to specify a single param for my method using query creation or should I implement custom logic to achieve this?
推荐答案
List<Person> findByFirstNameOrLastName(String firstName, String lastName);
是的,这是方法签名的问题.当方法名称中存在或"条件时,Spring Data 需要 2 个参数.并且您需要为两个参数传递一个 key
值.
Yes, it's an issue with the method signature. Spring Data expects 2 parameters when the "or" condition is present in a method name. And you need to pass a key
value for both parameters.
或者,您可以在该方法上编写一个 @Query
,例如:
Alternatively, you could write a @Query
over the method like:
@Query("SELECT p FROM person p WHERE p.lastName=:key OR p.firstName =:key")
List<AccountInformation> findByFirstNameOrLastName(@Param("key") String key);
这篇关于从方法名称生成查询的 Spring Data 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!