java 如何使用 JpaRepository 和嵌套的对象列表进行搜索?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47996810/
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 to search with JpaRepository and nested list of objects?
提问by DevDio
Description
描述
There is a PersonRepository
and Person
entity,
Person
class contains List<Qualification>
. Qualification
class has 3 simple fields.
有一个PersonRepository
andPerson
实体,
Person
类包含List<Qualification>
. Qualification
类有 3 个简单的字段。
I have tried to add @Query
annotation on custom method and use JPQL to get the results, but Qualification
class fields were not available for manipulation in JPQL as it repository itself contains List<Qualification>
instead of just a simple field of Qualification
.
我尝试@Query
在自定义方法上添加注释并使用 JPQL 来获取结果,但是Qualification
类字段不可用于在 JPQL 中进行操作,因为它存储库本身包含List<Qualification>
而不仅仅是一个简单的Qualification
.
How can I search by these Qualification's nested fields?
如何通过这些 Qualification 的嵌套字段进行搜索?
Query
询问
Now I need to find list of person entity where qualification's experienceInMonths is greater than 3 and less than 9 AND qualification's name field = 'java'.
现在我需要找到资格的 ExperienceInMonths 大于 3 且小于 9 且资格的名称字段 = 'java' 的人员实体列表。
Code
代码
Person.java
人.java
@Data
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
@NotEmpty
@Size(min = 2)
private String name;
@NotEmpty
@Size(min = 2)
private String surname;
@ElementCollection(targetClass = java.util.ArrayList.class, fetch = FetchType.EAGER)
private List<Qualification> qualifications = new ArrayList<>();
}
PersonRepository.java
PersonRepository.java
@Repository
public interface PersonRepository extends JpaRepository<Person, String> {
}
Qualification.java
资质.java
@Data
@AllArgsConstructor
public class Qualification implements Serializable {
@Id @GeneratedValue
private String id;
private String name;
private String experienceInMonths;
}
EDIT:not duplicate of this post, as here is the collection of nested objects. Not just single reference.
编辑:不是这篇文章的重复,因为这里是嵌套对象的集合。不仅仅是单一的参考。
回答by Cepr0
First, change experienceInMonths
from String
to int
(otherwise you can not compare the string with the number). Then you can try to use this 'sausage':
首先,改变experienceInMonths
从String
到int
(否则你不能比较数字字符串)。然后你可以尝试使用这个“香肠”:
List<Person> findByQualifications_experienceInMonthsGreaterThanAndQualifications_experienceInMonthsLessThanAndName(int experienceGreater, int experienceLess, String name);
Or you can try to use this pretty nice method:
或者你可以尝试使用这个非常好的方法:
@Query("select p from Person p left join p.qualifications q where q.experienceInMonths > ?1 and q.experienceInMonths < ?2 and q.name = ?3")
List<Person> findByQualification(int experienceGreater, int experienceLess, String name);