Two entities with @ManyToOne should join the same table
-
26-09-2019 - |
Question
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?
UPDATE
See my own solution below.
Solution 2
I've resolved my issue with the help of @SecondaryTable
and switched from @JoinTable
to @JoinColumn
:
Task
@Entity
@SecondaryTable(name="student_task")
public class Task implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(optional = false)
@JoinColumn(table = "student_task", name = "student_id")
private Student author;
@ManyToOne(optional = false)
@JoinColumn(table = "student_task", name = "teacher_id")
private Teacher curator;
//getters and setters
}
Now, generated SQL looks like:
insert
into
student_task
(student_id, teacher_id, id)
values
(?, ?, ?)
and everything works just fine :)
OTHER TIPS
I think you are missing the JoinColumns tag...
joinColumns = { @JoinColumn(name = "student_id", referencedColumnName = "id") }
joinColumns = { @JoinColumn(name = "teacher_id", referencedColumnName = "id") }
in author and curator respectively
Also remember, that the inversjoincolumn is the column in the owned table.. so it must be something like:
inverseJoinColumns = {@JoinColumn(name="id")})