JPA - OneToMany relationship not loading children

2019-08-21 23:54发布

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

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.

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();

Why?

2条回答
够拽才男人
2楼-- · 2019-08-22 00:20

fetch= FetchType.LAZY

Your collection is not loaded and the transaction has ended.

查看更多
甜甜的少女心
3楼-- · 2019-08-22 00:24

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. 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.

查看更多
登录 后发表回答