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

My tables look like this:

School
-------
school_id (pk)
...

Student
school_id (pk) (fk)
student_id (pk)
...

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

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

@Entity
@Table("STUDENT")
public Student {
    @EmbeddedId
    private StudentPK studentPK;

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

@Embeddable
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: https://stackoverflow.com/questions/67377494/how-do-i-map-a-one-to-many-relationship-with-composite-primary-key-in-jpa-hiber

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: