我有以下实体
学生
@Entity
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//getter and setter for id
}
老师
@Entity
public class Teacher implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//getter and setter for id
}
任务
@Entity
public class Task implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(optional = false)
@JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "student_id") })
private Student author;
@ManyToOne(optional = false)
@JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "teacher_id") })
private Teacher curator;
//getters and setters
}
考虑到author
并且curator
已经存储在数据库中并且两者都处于附加状态。我正在努力坚持我的Task
:
Task task = new Task();
task.setAuthor(author);
task.setCurator(curator);
entityManager.persist(task);
Hibernate 执行以下 SQL:
insert
into
student_task
(teacher_id, id)
values
(?, ?)
这当然会导致null value in column "student_id" violates not-null constraint
谁能解释这个问题以及解决它的可能方法?
更新
请参阅下面我自己的解决方案。