Two entities with @ManyToOne should join the same table
- by Ivan Yatskevich
I have the following entities
Student
@Entity
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//getter and setter for id
}
Teacher
@Entity
public class Teacher implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//getter and setter for id
}
Task
@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
}
Consider that author and curator are already stored in DB and both are in the attached state. I'm trying to persist my Task:
Task task = new Task();
task.setAuthor(author);
task.setCurator(curator);
entityManager.persist(task);
Hibernate executes the following SQL:
insert
into
student_task
(teacher_id, id)
values
(?, ?)
which, of course, leads to null value in column "student_id" violates not-null constraint
Can anyone explain this issue and possible ways to resolve it?