• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin

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

Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).


String category
Person person
Album album

List<AlbumCategorization> albums


With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic