membersound
membersound

Reputation: 86875

How to name the @ForeignKey when using @IdClass composite primary key?

@Entity
@IdClass(MyPK.class)
public class SubEntity {
    @Id private int id;
    @Id private String name;
}

@Entity
public class ParentEntity {
    @OneToOne(cascade = ALL)
    @JoinColumn(name="fk_sub_id", foreignKey = @ForeignKey(name="fk_sub"))
    private SubEntity sub;
}

Caused by: org.hibernate.AnnotationException: A Foreign key refering SubEntity from ParentEntity has the wrong number of column. should be 2

This fails due to the @JoinColumn annotation. But how do I have to write it for a composite PK? I have to use this annotation to set the foreignkey constraint name during hibernate auto generation.

Upvotes: 3

Views: 2173

Answers (1)

Aestel
Aestel

Reputation: 409

For composite keys you should use @JoinColumns

@JoinColumns(value = {
    @JoinColumn(name = "fk_sub_id", referencedColumnName = "id"),
    @JoinColumn(name = "fk_name", referencedColumnName = "name")},
    foreignKey = @ForeignKey(name = "fk_sub"))

Update:

Hibernate seems to not have followed the JPA 2.1 specification in this instance. You'll need to additionally include hibernates own annotation which is deprecated but still functions. This should be added like:

@JoinColumns(value = {
    @JoinColumn(name = "fk_sub_id", referencedColumnName = "id"),
    @JoinColumn(name = "fk_name", referencedColumnName = "name")},
    foreignKey = @ForeignKey(name = "fk_sub"))
@org.hibernate.annotations.ForeignKey(name = "fk_sub")

Upvotes: 2

Related Questions