简体   繁体   中英

Hibernate Parent/Child/Grandchild OneToMany Access

I'm trying to figure out how to set up hibernate for the following tables.

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

I have the configuration working to access the children from the parent (OneToMany) and the grandchildren from the child (OneToMany), however, I'm struggling with the mapping that allows me to access the grandchildren from the parent (OneToMany).

Here are the Hibernate mappings I currently have:

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;
}

You need to use the JoinTable annotation

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;
}

Now you can for example fetch all parents together with grandchildren:

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

It will produce following SQL query:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM