gpt4 book ai didi

java - 无法添加或更新子行: a foreign key constraint fails error when trying to save an entity and its relational entity

转载 作者:行者123 更新时间:2023-12-02 09:02:42 25 4
gpt4 key购买 nike

嗯,我的数据库中有以下表格:

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);

以及以下实体:

@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;

和:

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

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

当我创建一个 Movie 对象并设置所有属性(包括 Actor)并调用 save 方法时,我得到:“无法添加或更新子行:外键约束失败 (movieow. actor_movie,约束 FKsc6u9gs0762qyrnyfwp9d5q2b 外键 (movie_id) 引用 actor (actor_id)) ”

我希望当我保存 Movie 对象时,它会级联保存 actor 和 actor_movie 表。

我做错了什么?

最佳答案

这听起来像是不同实体不同步的问题(我没有针对您的情况进行测试)。这个想法是为您的集合创建添加和删除方法,以添加或删除相应关联对象中的实体。有关 @ManyToMany 关系的清晰示例,您可以查看 Vlad Mihalcea's article about these relationships 。关于synchronisation and cascading, he also wrote an article .

关于java - 无法添加或更新子行: a foreign key constraint fails error when trying to save an entity and its relational entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60046792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com