简体   繁体   中英

Cannot add or update a child row: a foreign key constraint fails error when trying to save an entity and its relational entity

Well, i have the following tables in my database:

CREATE TABLE movie (
movie_id INTEGER NOT NULL AUTO_INCREMENT,
translated_title VARCHAR(150),
original_title VARCHAR(150),
plot MEDIUMTEXT,
genre VARCHAR(150),
country VARCHAR(250),
language VARCHAR(100),
upvotes INTEGER,
premiere_year INTEGER(4),
duration_minutes Integer,
CONSTRAINT movie_pk PRIMARY KEY (movie_id));

CREATE TABLE actor (
actor_id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(150),
nationality VARCHAR(150),
born_date DATE,
CONSTRAINT actor_pk PRIMARY KEY (actor_id));

CREATE TABLE actor_movie (
actor_id INTEGER,
movie_id INTEGER,
FOREIGN KEY (actor_id) REFERENCES actor (actor_id) ON DELETE CASCADE,
FOREIGN KEY (movie_id) REFERENCES movie (movie_id) ON DELETE CASCADE);

and the following entities:

@Entity(name = "movie")
public class Movie implements Serializable {    

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "actor_movie",
        inverseJoinColumns  = { @JoinColumn(name = "actor_id", insertable = true, updatable = true)},
        joinColumns = { @JoinColumn(name = "movie_id", insertable = true, updatable = true) })
private Set<Actor> actors;

and:

@Entity(name = "actor")
public class Actor implements Serializable {

@ManyToMany(mappedBy="actors")
private Set<Movie> movies;

When i create a Movie object and set all properties, including an Actor and call the save method, i get: "Cannot add or update a child row: a foreign key constraint fails ( movieow . actor_movie , CONSTRAINT FKsc6u9gs0762qyrnyfwp9d5q2b FOREIGN KEY ( movie_id ) REFERENCES actor ( actor_id ))"

I want to when i save a Movie object, it saves in cascade the actor and actor_movie tables.

What am i doing wrong?

This sound like the problem that the different entities are not synchronised (I did not test it for your case). The idea is to create add and delete methods for your set which add or delete the entity in the respective associated object. For a clear example of @ManyToMany relationships, you could have a look at Vlad Mihalcea's article about these relationships . About synchronisation and cascading, he also wrote an article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM