描述
有PersonRepository和Person实体, Person类包含List<Qualification>。Qualification该类有3个简单字段。
PersonRepository
Person
List<Qualification>
Qualification
我尝试@Query在自定义方法上添加注释,并使用JPQL来获取结果,但是QualificationJPQL中无法使用类字段进行操作,因为它的存储库本身包含List<Qualification>而不是的简单字段Qualification。
@Query
如何通过这些“资格”的嵌套字段进行搜索?
询问
现在,我需要查找资格证书的experienceInMonths大于3且小于9并且资格证书的名称字段=’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
@Repository public interface PersonRepository extends JpaRepository<Person, String> { }
Qualification.java
@Data @AllArgsConstructor public class Qualification implements Serializable { @Id @GeneratedValue private String id; private String name; private String experienceInMonths; }
首先,experienceInMonths从更改String为int(否则您无法将字符串与数字进行比较)。然后,您可以尝试使用此“香肠”:
experienceInMonths
String
int
List<Person> findByQualifications_experienceInMonthsGreaterThanAndQualifications_experienceInMonthsLessThanAndName(int experienceGreater, int experienceLess, String name);
或者,您可以尝试使用这种非常不错的方法:
@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);