0

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.

4

3 回答 3

0

没关系,这是一个 Datanucleus 错误。它已在 datanucleus-rdbms-3.2.6 中修复。这是修复的提交:

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

于 2013-09-02T08:51:19.863 回答
0

您需要在 Child 类中使用 @JoinColumn 并尝试此操作。

家长:

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

当您从父表中获取数据时,它将自动包含来自 Set 'children' 中子表的关联数据

于 2013-08-29T07:20:25.943 回答
0
  1. 您需要@JoinColumn创建双向关系:

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

  2. 如果您使用的是 JPA 注释select c from Child c,那么child.getParent()数据库中的对象就足够了。

于 2013-08-28T21:36:37.260 回答