As I understand your request, you would like the mentor to be the owner of the relationship. You will not get this with the line @OneToMany(mappedBy="mentor") . This actually puts the student as the owner of the relationship.
I tested this domain model and made several modifications to the annotations so that the test code works as you expect.
Student
public class Student implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy= GenerationType.AUTO) private int id; private String name; @ManyToOne @JoinColumns({ @JoinColumn(name="name_fk", referencedColumnName="name", insertable = false, updatable = false), @JoinColumn(name="address_fk", referencedColumnName="address", insertable = false, updatable = false ) }) private Mentor mentor;
Mentor
public class Mentor implements Serializable { private static final long serialVersionUID = 1L; @Id private MentorPK id; private String email; @OneToMany(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name="name_fk", referencedColumnName="name"), @JoinColumn(name="address_fk", referencedColumnName="address") }) private Set<Student> students;
It even works without execution: s1.setMentor(m);s2.setMentor(m); . I did not expect this, but it seems that sleep mode is coping with this.
Related article here .
Caution: delete database tables after changing annotations to allow hibernate to recreate tables.
Cristian sevescu
source share