kabal
kabal

Reputation: 2145

JPA: Non unique "OneToMany" collection

I want to map a "collection". A collection is a group of items that the user can group as they wish.

@Entity 
class Item {
  Long id;
  String name
}

@Entity 
class MyCollection {
  Long id;
  String name;

  @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  Set<Item> items;
}

The user should be able to put Item name "foo" into `MyCollection' name "bar" and into 'MyCollection' name "bar2"

The join table that JPA/Hibernate is creating for me, MyCollection_Item has has 4 indexes, the PK (MyCollection_id, Item_id), a unique index (Item_id), and the 2 foreign keys.

I do not want it to create the unique index on Item_id. This prevents me from having:

MyCollection_id, Item_Id

1, 1

1, 2

2, 1

I am sure this type of mapping must be possible? Any help would be greatly appreciated.

Upvotes: 4

Views: 2111

Answers (2)

BobTheBuilder
BobTheBuilder

Reputation: 19284

OneToMany is when you want to map one object to many objects

ManyToMany is when you want to map many object to many objects (like you try to do here)

Upvotes: 1

digitaljoel
digitaljoel

Reputation: 26574

You need a ManyToMany but you have it mapped as a OneToMany.

Upvotes: 0

Related Questions