![](/img/trans.png)
[英]Parent id not insert to child table whit OneToMany relationship in java hibernate
[英]Hibernate @OneToMany - child owns the relationship, but only has the parents id
我在父 class 上定義了一個 @OneToMany 關系,如下所示:
public class Course {
@OneToMany(
mappedBy = "courseId",
fetch = FetchType.EAGER,
cascade = CascadeType.ALL,
orphanRemoval = true)
private Set<Student> students;
}
在關系的另一邊,我只保留父實體的 id:
public class Student {
private Long courseId;
}
當我與新學生一起保存課程時,hibernate 首先保留課程,然后嘗試保留每個學生,這是我所期望的。 (我可以通過 hibernate 日志記錄看到這一點。)
但是,當它插入每個學生時,它為courseId
null
數據庫最終拋出此錯誤: ERROR: null value in column "courseid" violates not-null constraint
我在代碼中還有其他示例可以正常工作,但由於某種原因,此示例的行為有所不同。
是否有理由不使用剛剛保存的課程中的 ID? 我需要添加一些其他配置來支持這個嗎?
我認為您需要更改您的Student
class:
public class Student {
@ManyToOne
@JoinColumn(name="course_id", nullable=false)
private Course course;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.