• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

JPA: multiple many-to-many realationships between same two tables?

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

 
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
The fastest and most reliable components of any system are those that are not there. Tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!