本文介绍了如何使用JpaRepository和对象的嵌套列表进行搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明

有一个PersonRepositoryPerson实体,Person类包含List<Qualification>. 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>而不是一个简单的字段的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.

如何通过这些资格"的嵌套字段进行搜索?

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.

推荐答案

首先,将experienceInMonthsString更改为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);

这篇关于如何使用JpaRepository和对象的嵌套列表进行搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 19:11