JPA - OneToMany relationship not loading children

2019-08-22 00:22发布

问题:

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?

回答1:

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.



回答2:

fetch= FetchType.LAZY

Your collection is not loaded and the transaction has ended.