Chris Vilches
Chris Vilches

Reputation: 1187

ManyToMany relationship not persisting in JPA when adding a new one

I have this piece of code which adds an entry to film_actor (in theory), but it doesn't work. This code doesn't crash, but doesn't save the added entry to the database.

    Actor nuevo = ActorFacadeEJB.find(actor_id);
    Film pelicula = FilmFacadeEJB.find(film_id);

    pelicula.getActors().add(nuevo);

Also I have this code:

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "film_actor", joinColumns = { @JoinColumn(name = "film_id") }, inverseJoinColumns = {
            @JoinColumn(name = "actor_id") })   
    private Set<Actor> actors;


    public Set<Actor> getActors() {
        return actors;
    }

The actor also has a film set:

@ManyToMany(mappedBy="actors")
private Set<Film> film= new HashSet<Film>();

How can I fix all this to make it work? I googled it, and many people have similar code to mine, but just mine doesn't work.

Upvotes: 0

Views: 492

Answers (2)

Steve C
Steve C

Reputation: 19445

You need to assign both sides of the relationship:

pelicula.getActors().add(nuevo);
nuevo.getFilms().add(película);

Upvotes: 0

arjun99
arjun99

Reputation: 358

Make sure your Annotations are proper as below :
@Entity
@Table(name="film")
class Film{
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name="film_actor", 
                joinColumns={@JoinColumn(name="film_id")}, 
                inverseJoinColumns={@JoinColumn(name="actor_id")})
 private Set<Actor> actors=new HashSet<Actor>;
}

@Entity
@Table(name="actor")
class Actor{
@ManyToMany(mappedBy="actors")
    private Set<Film> film= new HashSet<Film>();
}

Upvotes: 1

Related Questions