How do I map a One To Many Relationship with Composite Primary Key in JPA (Hibernate)?

My tables look like this:

school_id (pk)

school_id (pk) (fk)
student_id (pk)

So using JPA (Hibernate), I tried something like this.

public School {
    @Column(name = "SCHOOL_ID")
    private String schoolId;
    private List<Student> students;

public Student {
    private StudentPK studentPK;

    @JoinColumn(name = "SCHOOL_ID")
    private School school; 

public StudentPK implements Serializable {
    @Column(name = "SCHOOL_ID")
    private String schoolId;

    @Column(name = "STUDENT_ID"
    private String studentId;

When I do this, I frequently get an error that says that the foreign key constraint is being violated on runtime. I suspect that JPA is trying to generate a new foreign key called "SCHOOL_ID" instead of using the existing column from my composite key, but I'm not sure how to force it to use the existing column.

Read more here:

Content Attribution

This content was originally published by Jensen Lo at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: