我正在使用 hibernate 处理一对多关系。
教授.java
@Entity
public class Profesor {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@ManyToMany(mappedBy = "profesors", fetch = FetchType.EAGER, cascade = { CascadeType.MERGE, CascadeType.PERSIST })
private List<Classes> classes;
@OneToMany(mappedBy="profesor", fetch = FetchType.EAGER, cascade = { CascadeType.MERGE, CascadeType.PERSIST })
@Fetch(value = FetchMode.SUBSELECT)
private List<Post> post;
}
我的教授表已经与类(class)表建立了多对多的关系。现在我尝试将其与帖子表作为一对多连接。
我的帖子模型如下所示:
post.java
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", unique = true, nullable = false)
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn (name="profesor_id",referencedColumnName="id",nullable=false,unique=true)
private Profesor profesor;
}
这是我的表格帖子在数据库中的外观。
我收到以下错误:
Cannot add or update a child row: a foreign key constraint fails (`database`.`#sql-45e3_695`, CONSTRAINT `FKfkqyncksuk5vuw09wam4sryyd` FOREIGN KEY (`profesor_id`) REFERENCES `profesor` (`id`))
我做错了什么?
<小时/>解决方案:
首先,我创建了没有 profesor_id 的帖子表。我在开始创建表之间的关系时添加了profesor_id,然后profesor_id设置为null。当我清理 table 后,我可以正常运行我的应用程序。
最佳答案
很明显你违反了一些限制,我想说你正在尝试删除已经链接到帖子的教授,尝试删除 nullable = false
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn (name="profesor_id",referencedColumnName="id",unique=true)
private Profesor profesor;
关于java - 无法添加或更新子行: a foreign key constraint fails - One-To-Many relationship - Hibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45723613/