| Author |
JPA: multiple many-to-many realationships between same two tables?
|
Per Lindberg
Ranch Hand
Joined: Jan 17, 2008
Posts: 48
|
|
Is it possible to have more than one many-to-many relationship between two entities in JPA (or JPA2)?
Let's say that we want to model musical preferences. We have the two entities Person and Album.
If we just want to model who owns what album then we can have a plain vanilla many-to-many relationship
between the two.
But now we also want to keep track of how each Person would categorize each album. To make things worse, we don't know beforehand which categories a Person wants to use. So each Person would have a couple of sets of Albums, one for each category he has invented. Perhaps a Map<String,List<Album>>?
I would think that the DB would have a join table with an extra field for the category, right?
But can that be annotated in the entities using JPA?
|
 |
James Sutherland
Ranch Hand
Joined: Oct 01, 2007
Posts: 550
|
|
Yes, it is possible to have multiple ManyToMany relationships between two entities. Each relationship would have its own join table. The default name of the join table may be the same, so you would need to specify the @JoinTable's name.
But this does not seem to be what you are asking for. You want a Map<String, List<Album>>, or a nested collection. JPA does not support this. A @MapColumn is supported in JPA 2.0, but not to a nested collection. Your best solution is to model the join table as an Entity (or possibly an Embeddable if you use an ElementCollection).
i.e.
AlbumCategorization
String category
@ManyToOne
@Id
Person person
@ManyToOne
@Id
Album album
Person
@OneToMany
List<AlbumCategorization> albums
See,
http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany#Mapping_a_Join_Table_with_Additional_Columns
http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Nested_Collections.2C_Maps_and_Matrices
|
TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
|
 |
 |
|
|
subject: JPA: multiple many-to-many realationships between same two tables?
|
|
|