[英]Hibernate @OneToMany - child owns the relationship, but only has the parents id
I have a @OneToMany relationship defined on the parent class like so:我在父 class 上定义了一个 @OneToMany 关系,如下所示:
public class Course {
@OneToMany(
mappedBy = "courseId",
fetch = FetchType.EAGER,
cascade = CascadeType.ALL,
orphanRemoval = true)
private Set<Student> students;
}
On the other side of the relationship, I simply keep the id of the parent entity:在关系的另一边,我只保留父实体的 id:
public class Student {
private Long courseId;
}
When I save a Course with new Students, hibernate first persists the Course, and then tries to persist each Student which is what I would expect.当我与新学生一起保存课程时,hibernate 首先保留课程,然后尝试保留每个学生,这是我所期望的。 (I can see this via hibernate logging.) (我可以通过 hibernate 日志记录看到这一点。)
However, when it goes to insert each Student, it is passing a null
for the courseId
.但是,当它插入每个学生时,它为courseId
null
The database ends up throwing this error: ERROR: null value in column "courseid" violates not-null constraint
I have other examples of this working correctly in the code, but for some reason this one is behaving differently.数据库最终抛出此错误: ERROR: null value in column "courseid" violates not-null constraint
我在代码中还有其他示例可以正常工作,但由于某种原因,此示例的行为有所不同。
Is there a reason it's not using the id from the Course it just saved?是否有理由不使用刚刚保存的课程中的 ID? Is there some other configuration I need to add to support this?我需要添加一些其他配置来支持这个吗?
I think you need to change your Student
class:我认为您需要更改您的Student
class:
public class Student {
@ManyToOne
@JoinColumn(name="course_id", nullable=false)
private Course course;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.