Java 如何使用包含关键字的属性创建 Spring JPA 存储库 findBy 查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33153271/
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
How do you create a Spring JPA repository findBy query using a property that contains a keyword?
提问by Ben M.
Here is a simplified example of my problem. I have this repository and entity class.
这是我的问题的简化示例。我有这个存储库和实体类。
public interface ThingRepository extends JpaRepository<ThingEntity, Long> {
ThingEntity findByFooInAndBar(String fooIn, String bar);
}
@Entity
public class ThingEntity {
@Column(name="FOO_IN", nullable=false, length=1)
private String fooIn;
public String getFooIn() {
return fooIn;
}
public setFooIn(String fooIn) {
this.fooIn = fooIn;
}
/* not including bar property for brevity's sake */
}
Spring is throwing the following exception.
Spring 抛出以下异常。
org.springframework.data.mapping.PropertyReferenceException: No property foo found for type ThingEntity!
It looks like Spring is taking the method findByFooInAndBar
and thinks that foo
is my property name and in
is a keyword for matching values within a collection.
看起来 Spring 正在采用该方法findByFooInAndBar
并认为这foo
是我的属性名称,并且in
是用于匹配集合中值的关键字。
How do I get it to understand that the property name is fooIn
, not foo
?
我如何才能理解属性名称是fooIn
,不是foo
?
采纳答案by Ben M.
To overcome this problem, I've defined the query manually using the @Query
annotation. I'll happily accept anyone else's answer if they find a solution that doesn't require a manual query.
为了克服这个问题,我使用@Query
注释手动定义了查询。如果他们找到不需要手动查询的解决方案,我会很乐意接受其他人的回答。
public interface ThingRepository extends JpaRepository<ThingEntity, Long> {
@Query("SELECT t FROM Thing t WHERE t.fooIn = ?1 AND t.bar = ?2")
ThingEntity findByFooInAndBar(String fooIn, String bar);
}
回答by Oscar E. Rodríguez Gómez
Spring is parsing 'In' in your method to create the query check the link for create your query you should change the name of the variable fooIn to fooin or something like that....
Spring 正在您的方法中解析“In”以创建查询检查链接以创建您的查询您应该将变量 fooIn 的名称更改为 fooin 或类似的名称....
回答by Rog Tebs
I observed the code kindly and notice your return is not a list
but an object
.
Change that part to List<ThingEntity>
.
我友好地观察了代码,并注意到您的返回不是 alist
而是object
。
将该部分更改为List<ThingEntity>
.