简体   繁体   中英

JPA - OneToMany relationship not loading children

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?

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

All entities need to have an @Id field and a empty constructor.

If you use custom sql scripts for initialize your database you need to add the annotation @JoinColumn on each fields who match a foreign key :

example :

class Parent {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    public Parent() {}

    /* Getters & Setters */
}

class Child {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;


    /* name="<tablename>_<column>" */
    @JoinColumn(name="Parent_id", referencedColumnName="id")
    private int foreignParentKey;

    public Child () {}
}

fetch= FetchType.LAZY

Your collection is not loaded and the transaction has ended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM