Take the 2-minute tour ×

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:

public class Parent {
    private int id;

    private String title;

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

    private int id;

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


The equivalent SQL query executed by datanucleus is:


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


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.

share|improve this question
If you just want the parent and you have the child, you can say FROM Parent p WHERE p.id = :parent_id –  Martin Wickham Aug 28 '13 at 21:09
I would like the child and the parent in one single query/transaction –  user1057128 Aug 28 '13 at 22:21
add comment

3 Answers

  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.

share|improve this answer
I'm looking for a way to get the child and it's parent in one query, ie as a join. Your suggested solution in point 2 executes two separate queries. –  user1057128 Aug 28 '13 at 22:20
add comment

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


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


@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'

share|improve this answer
This makes no difference –  user1057128 Aug 29 '13 at 10:52
I don't why it doesn't make any change but I have tried in this way it worked for me. –  Praveen P. Moolekandathil Aug 29 '13 at 11:00
add comment
up vote 0 down vote accepted

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


share|improve this answer
add comment

Your Answer


