JPA-OneToMany关系未加载子级 [英] JPA - OneToMany relationship not loading children

查看:291
本文介绍了JPA-OneToMany关系未加载子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试配置此@OneToMany和@ManyToOne关系,但它根本无法正常工作,不确定为什么.我之前在其他项目上已经完成了此操作,但是由于某种原因它无法在当前配置下正常工作,下面是代码:

I am trying to configure this @OneToMany and @ManyToOne relationship but it's simply not working, not sure why. I have done this before on other projects but somehow it's not working with my current configuration, here's the code:

public class Parent {
   @OneToMany(mappedBy = "ex", fetch= FetchType.LAZY, cascade=CascadeType.ALL)
   private List<Child> myChilds;

   public List<Child> getMyChilds() {
         return myChilds;
   }
}

public class Child {
   @Id
   @ManyToOne(fetch=FetchType.LAZY)    
   private Parent ex;
   @Id
   private String a;
   @Id
   private String b;

   public Parent getParent(){
         return ex;
   }
}

起初,我认为可能是导致故障的三元@Id注释,但是删除注释后,它仍然不起作用.因此,如果有人有任何想法,我将使用EclipseLink 2.0.

At first, I thought it could be the triple @Id annotation that was causing the malfunction, but after removing the annotations it still doesn't work. So, if anyone have any idea, I am using EclipseLink 2.0.

我只是尝试用一些记录执行代码,并且它返回s == 0 总是:

I just try to execute the code with some records and it returns s==0 always:

Parent p = new Parent();
Integer s = p.getMyChilds().size();

为什么?

推荐答案

问题很可能出在您的保存中,因为您必须在要保存的子对象中设置父对象引用,而不要在您的检索或实体中设置父对象引用本身的映射. 可以从数据库行中确认这一点,该数据库行在您孩子的表的外键列中必须为null.例如妥善保存

The problem most probably is in your saving because you must not be setting the parent object reference in the child you want to save, and not with your retrieval or entity mappings per se. That could be confirmed from the database row which must be having null in the foreign key column of your child's table. e.g. to save it properly

Parent p = new Parent();
Child child = new Child();
p.setChild(child);
child.setParent(p);
save(p);

PS.最好将@JoinColumn(name = "fk_parent_id", nullable = false)@ManyToOne注释一起使用.设置要导致他们在尝试检索时未命中的值的错误,这将停止错误.

PS. It is good practice to use @JoinColumn(name = "fk_parent_id", nullable = false) with @ManyToOne annotation. This would have stopped the error while setting the value which resulted in their miss while you are trying to retrieve.

这篇关于JPA-OneToMany关系未加载子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆