简体   繁体   中英

JPA: fetching bidirectional many to one relationship

I'm a beginner to the JPA/JPQL stuff and I'm having problems fetching many-to-one relationships when I make the relationship bi-directional. Here is the JPQL:

select c from Child c join fetch c.parent

Here are the two simple classes:

@Entity
public class Parent {
    @Id
    private int id;

    private String title;

    @OneToMany(mappedBy = "parent")
    private Set<Child> children;
}
@Entity
public class Child {

    @Id
    private int id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Parent parent;

}

The equivalent SQL query executed by datanucleus is:

SELECT 'com.*.Child' AS NUCLEUS_TYPE,`C`.`ID`,`C`.`PARENT_ID` FROM `CHILD` `C` INNER JOIN `PARENT` `B0` ON `C`.`PARENT_ID` = `B0`.`ID`

Now if I completely remove the reference to "children" in Parent, the SQL is exactly what I need:

SELECT 'com.*.Child' AS NUCLEUS_TYPE,`C`.`ID`,`B0`.`ID`,`B0`.`TITLE` FROM `CHILD` `C` INNER JOIN `PARENT` `B0` ON `C`.`PARENT_ID` = `B0`.`ID`


To be clear: what I'm trying to achieve is to fetch the child's parent with my JPQL query.

Update: I just tried these two classes with EclipseLink and this works, so looks like this problem is Datanucleus-specific.

  1. You need @JoinColumn to create bidirectional relation:

    @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") private Parent parent;

  2. If you are using JPA annotations select c from Child c and than child.getParent() on objects from database should be enough.

You need to use @JoinColumn in the Child class and try this.

Parent:

@OneToMany(targetEntity = Child.class, fetch = FetchType.EAGER, mappedBy = "parent", cascade=CascadeType.ALL)

Child:

@ManyToOne(targetEntity=Parent.class, fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="id", nullable = false)

And when you fetch the data from parent table it will automatically contains the associated data from the child table in the Set 'children'

Nevermind, this was a Datanucleus bug. It has been fixed in datanucleus-rdbms-3.2.6. This is the commit for the fix:

http://sourceforge.net/p/datanucleus/code/18118/

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