0

I would like to know if it is possible to use a Map in a @ManyToMany relationship.

For instance, consider the entities Movie and Person:

public class Movie implements Serializable {

...

    @ManyToMany(mappedBy="actor_roles")
    private Set<Person> cast;

...
}

and now Person.java:

public class Person implements Serializable {

...

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "Person_Movie_Actor", 
             joinColumns = { @JoinColumn(name = "person_id") }, 
             inverseJoinColumns = { @JoinColumn(name = "movie_id") })
    private Set<Movie> actor_roles;

...
}

The issue is that I want to preserve this many-to-many relationship, but I also want to hold a mapping [Person ==> Role] per Movie. Something like this I guess:

@ManyToMany(mappedBy="actor_roles")
private Map<Person, String> cast;

where the String would be something like "Neo", "Inspector Gadjet", "Don Corleone",... you get the idea.

What is the best way to get such mapping? Of course, I could create a new attribute in the Person entity

private Map<Movie, String> roles;

but this approach feels like I would be duplicating data as result of bad design. Any ideas?

nmpg
  • 561
  • 2
  • 10
  • 24
  • 1
    I think the best strategy here is to introduce another entity (Movie, Person, Role). There is [@ElementCollection](http://stackoverflow.com/questions/3393649/storing-a-mapstring-string-using-jpa), but that's only suitable for simple types, like String. – jabu.10245 Nov 30 '15 at 17:59
  • 1
    @nmpg: What about double roles? From my point of view a `Map` makes more sense. – Tobias Liefke Nov 30 '15 at 20:22
  • 1
    @jabu.10245 `Embeddable` can be used for `@ElementCollection` as well. – Tobias Liefke Nov 30 '15 at 20:23
  • @TobiasLiefke yeah, good catch, haven't thought of that. This is maybe the best way to go. Will dig further into this. – nmpg Dec 01 '15 at 09:20
  • Down-side of using this Map is that I don't get an index of the roles played by Actor X.. Using another entity as per @jabu.10245 suggestion seems to give me that ability however.. need to think carefully about this. – nmpg Dec 01 '15 at 09:34

0 Answers0