Hibernate父/子/孙子OneToMany访问

时间:2014-12-30 08:33:34

标签: java hibernate orm one-to-many

我正在试图弄清楚如何为下面的表设置hibernate。

CREATE TABLE parent (
  id BIGINT
);
CREATE TABLE child (
  id BIGINT,
  parent_id BIGINT
);
CREATE TABLE grandchild (
  id BIGINT,
  child_id BIGINT
);

我有配置工作来访问来自父(OneToMany)的孩子和来自孩子的孙子(OneToMany),但是,我正在努力使用允许我从父母(OneToMany)访问孙子的映射

以下是我目前拥有的Hibernate映射:

public class Parent {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "child") //This is the mapping that doesn't work
    private Set<Grandchild> grandchildren;
}
public class Child {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    private Parent parent;
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "child")
    private Set<Grandchild> grandchild;
}
public class Grandchild {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "child_id", referencedColumnName = "id")
    private Child child;
}

1 个答案:

答案 0 :(得分:0)

您需要使用JoinTable注释

public class Parent {
    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable
    (
        name="child",
        joinColumns={ @JoinColumn(name="parent_id", referencedColumnName="id") },
        inverseJoinColumns={ @JoinColumn(name="id", referencedColumnName="child_id") }
    )
    private Set<Grandchild> grandchildren;
}

现在您可以例如与孙子孙女一起获取所有父母:

em.createQuery("select p from Parent p inner join fetch p.grandchildren").getResultList();

它将生成以下 SQL 查询:

select
    parent0_.ID as ID2_0_,
    grandchild2_.ID as ID1_1_,
    grandchild2_.child_id as child2_1_1_,
    grandchild1_.parent_id as parent1_2_0__,
    grandchild1_.id as id0__ 
from
    Parent parent0_ 
inner join
    child grandchild1_ 
        on parent0_.ID=grandchild1_.parent_id 
inner join
    Grandchild grandchild2_ 
        on grandchild1_.id=grandchild2_.child_id