JPA和ManyToMany递归关系会导致查询错误

时间:2018-03-27 17:44:25

标签: java hibernate jpa

在Hibernate版本5中,我有一个带有递归ManyToMany的简单实体,当我对关系执行join fetch时,我得到一个带有两个连接的查询。我认为只需要一次加入。知道为什么要生成两个连接或者如何修复它?

@Entity
public class Employee implements Comparable<Employee> {
    @Id Integer id;    
    @ManyToMany
    protected Set<Employee> opinionCitations;
    // getters, setters
}

em.createQuery("select distinct e from Employee e left join fetch e.opinionCitations").getSingleResult();

给了我

select distinct 
    employee0_.id as id1_0_0_, 
    employee2_.id as id1_0_1_, 
    opinioncit1_.Employee_id as Employee1_1_0__, 
    opinioncit1_.opinionCitations_id as opinionC2_1_0__ 
from 
    Employee employee0_ 
    left outer join Employee_Employee opinioncit1_ on employee0_.id=opinioncit1_.Employee_id 
    left outer join Employee employee2_ on opinioncit1_.opinionCitations_id=employee2_.id

1 个答案:

答案 0 :(得分:0)

没有没有错。它将Employee表与链接表Employee_Employee连接,然后返回Employee。就像你期望@ManyToMany一样。

使用@OneToMany,您可以通过单个联接逃脱,因为它不需要链接表,但是您有一个树结构可能不是什么你想要的。