Search code examples
javajpaeclipselinkone-to-many

JPA Multiple OneToMany relations to the same Entity


I am trying to build a JPA Application. I basically have

@Entity
public class Folder {
  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  private int id;
  private String description;
  private String name;

  @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
  private List<AbstractItem> items = new LinkedList<AbstractItem>();

  @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
  private List<AbstractItem> items2 = new LinkedList<AbstractItem>();
  .
  .
  .
}

i can successfully add one Item to the item List, and persist it. However if i load it again, the same Object of the persistet Item is in both Lists items and items2.

I tried to fix this by adding a @JoinTable annotation, but i couldn't get it to work.

any suggestions?


Solution

  • You should have two references to the 'Folder' in your AbstractItem, for each case. Thus, mappedBy values should be specified accordingly, e.g.:

      @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
      private List<AbstractItem> items = new LinkedList<AbstractItem>();
    
      @OneToMany(mappedBy = "parent2", cascade = CascadeType.PERSIST)
      private List<AbstractItem> items2 = new LinkedList<AbstractItem>();