如何使用 JpaRepository 和嵌套的对象列表进行搜索?
说明
有一个PersonRepository
和Person
实体,Person
类包含 List
.Qualification
类有 3 个简单字段.
There is a PersonRepository
and Person
entity,
Person
class contains List<Qualification>
. Qualification
class has 3 simple fields.
我尝试在自定义方法上添加 @Query
注释并使用 JPQL 获取结果,但 Qualification
类字段在 JPQL 中不可用于操作,因为它是存储库本身包含 List
而不仅仅是 Qualification
的简单字段.
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
.
如何通过这些 Qualification 的嵌套字段进行搜索?
How can I search by these Qualification's nested fields?
查询
现在我需要找到资格的 experienceInMonths 大于 3 且小于 9 且资格的名称字段 = 'java' 的人员实体列表.
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'.
代码
Person.java
Person.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
Qualification.java
@Data
@AllArgsConstructor
public class Qualification implements Serializable {
@Id @GeneratedValue
private String id;
private String name;
private String experienceInMonths;
}
不重复 这篇文章,因为这里是嵌套对象的集合.不仅仅是单一参考.
not duplicate of this post, as here is the collection of nested objects. Not just single reference.
推荐答案
首先,将 experienceInMonths
从 String
改为 int
(否则你可以不要将字符串与数字进行比较).然后你可以尝试使用这个香肠":
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':
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);
相关文章