Simiil
Simiil

Reputation: 2311

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?

Upvotes: 8

Views: 9164

Answers (2)

Giovani Guizzo
Giovani Guizzo

Reputation: 527

Your mappedBy attribute is linking to a unique property named parent of AbstractItem, in other words, you are linking AbstractItem and Folder by the same attribute.
If you map the second list as parent2, there will be 2 foreign keys in AbstractItem to Folder table.
Use two associative tables (for items and items2) if you don't want a new property and a new column in AbstractItem.

Upvotes: 1

Art Licis
Art Licis

Reputation: 3679

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

Upvotes: 6

Related Questions