我在父类上定义了一个@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;
}
当我保存与新学生一起的课程时,休眠状态首先保留该课程,然后尝试保留每个学生,这正是我所期望的。 (我可以通过休眠日志记录看到这一点。)
但是,当要插入每个学生时,它会为null
传递一个courseId
。数据库最终抛出此错误:
ERROR: null value in column "courseid" violates not-null constraint
我还有其他示例可以在代码中正常工作,但是由于某些原因,该示例的行为有所不同。
是否有一个原因没有使用刚刚保存的课程中的ID?我需要添加其他一些配置来支持此功能吗?
答案 0 :(得分:0)
我认为您需要更改Student
类:
public class Student {
@ManyToOne
@JoinColumn(name="course_id", nullable=false)
private Course course;
}