如何创建同时在主表行和子行中搜索具有OneToMany关系的JPA查询

时间:2019-07-09 08:29:47

标签: java sql spring-boot jpa

我有两个实体。其中一个是另一个与OneToMany有关系的孩子。是否可以在主要实体和所有子实体中实施同时查找的搜索条件?

示例:  我的公司有很多员工。如果我搜索某些文本,则要检索所有公司,这些公司的标题包含该文本,或者其雇员姓名包含该文本。

以下是示例实体:

@Entity
public class Company extends AbstractEntity {
    @Column(nullable = false, unique = true)
    private String uuid;

    @Column(nullable = false)
    private String companyName;

    @OneToMany(mappedBy = “company”, cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
    protected Set<Employee> employees = new HashSet<>();

}

@Entity
public class Employee extends AbstractEntity {
    @Column(nullable = false, unique = true)
    private String uuid;

    @Column(nullable = false)
    private String firstName;

    @Column(nullable = false)
    private String lastName;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = “company_id”, nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Company company;
}

这是示例查询,不起作用:(

@Query(value = “SELECT c from Company c WHERE c.companyName LIKE CONCAT('%',:text,'%') or (SELECT e from c.employees e WHERE e.firstName  LIKE CONCAT('%',:text,'%')  OR  e.lastName  LIKE CONCAT('%',:text,'%'))”)
List<Company> findByText( @Param(“text” String text)

1 个答案:

答案 0 :(得分:1)

我认为您所需要的只是在这里加入左键:

@Query(value = “SELECT c from Company c left outer join c.employees e 
                WHERE c.companyName LIKE CONCAT('%',:text,'%') 
                  or e.firstName  LIKE CONCAT('%',:text,'%')  
                  or  e.lastName  LIKE CONCAT('%',:text,'%')”)