I\'m working with Spring framework. I have two entities, Movie and Actor, so a Movie can have many actors and an Actor can play in many Movie. Following we have the classes:
There are 2 issues here.
Firstly, you have not set the cascade options on the relationship.
@ManyToMany(mappedBy = "movies", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private List actors;
Secondly, in the case of a bi-directional relationship it is your responsibility to maintain both sides of the relationship in the in-memory model. The relationship here is being managed by Actor (the side without mappedBy
) but you have not added any movies to the movies collection in Actor.
So, if you iterate actors in your movies constructor and add the movie a.getMovies().add(this)
then both sides will be set and the data should be saved as requested.
The Hibernate docs suggest @ManyToMany
mappings should be avoided as in most cases you are likely to want to store additional data related to the association: in your case for example, character name. A more flexible option is then to create a Join Entity, say, MovieAppearance which has Movie, Actor, and other properties as required.