【问题标题】:Hibernate @OneToMany - child owns the relationship, but only has the parents idHibernate @OneToMany - 孩子拥有关系,但只有父母 id
【发布时间】:2020-05-01 21:30:59
【问题描述】:

我在父类上定义了一个@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 首先保留课程,然后尝试保留每个学生,这正是我所期望的。 (我可以通过休眠日志看到这一点。)

但是,当它插入每个学生时,它为courseId 传递了一个null。数据库最终抛出此错误: ERROR: null value in column "courseid" violates not-null constraint 我在代码中还有其他可以正常工作的示例,但由于某种原因,这个示例的行为有所不同。

它没有使用刚刚保存的课程中的 ID 是否有原因?我需要添加一些其他配置来支持这一点吗?

【问题讨论】:

标签: java spring hibernate orm


【解决方案1】:

我认为您需要更改 Student 课程:

public class Student {

    @ManyToOne
    @JoinColumn(name="course_id", nullable=false)
    private Course course;
}

【讨论】:

    猜你喜欢
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多