Override foreign key name pointing to JPA / hibernate composite key
I am using spring-boot 1.5.4 with spring-data-jpa and I am trying to override the auto-generated foreign key name during spring.jpa.hibernate.ddl-auto=create
.
For a simple id, I was able to override it: simple_fk
Hibernate: alter table my_entity add constraint simple_fk foreign key (simple_id) references simple
But not for a foreign key with a composite identifier: FKms12cl9ma3dk8egqok1dasnfq
Hibernate: alter table my_entity add constraint FKms12cl9ma3dk8egqok1dasnfq foreign key (composite_id1, composite_id2) references composite
What's wrong with my code? I have also tried @PrimaryKeyJoinColumn
.
See class definitions below.
@Entity
public class Simple {
@Id
private long id;
}
@Entity
public class Composite {
@Id
private CompositeId id;
}
@Embeddable
public class CompositeId {
@Column
private long id1;
@Column
private long id2;
}
@Entity
public class MyEntity {
@ManyToOne
@JoinColumn(foreignKey = @ForeignKey(name = "simple_fk"),
name = "simple_id", referencedColumnName = "id")
private Simple simple;
@ManyToOne
@JoinColumns(foreignKey = @ForeignKey(name = "composite_fk"), value = {
@JoinColumn(name = "composite_id1", referencedColumnName = "id1"),
@JoinColumn(name = "composite_id2", referencedColumnName = "id2")
})
private Composite composite;
}
source to share
This is a known issue with Hibernate and has been fixed in 5.2.8
So, there are two ways to fix this, either you upgrade Hibernate to 5.2.8, or you add
<hibernate.version>5.2.10.Final</hibernate.version>
to your pom.xml which will basically update Hibernate to the latest version.
or if updating Hibernate is not possible or just too risky, you can add a deprecated / deprecated annotation @org.hibernate.annotations.ForeignKey(name = "composite_fk")
to yours
composite
, which will make the code look like
@Entity
public class MyEntity {
@ManyToOne
@JoinColumn(foreignKey = @ForeignKey(name = "simple_fk"), name = "simple_id", referencedColumnName = "id")
private Simple simple;
@ManyToOne
@JoinColumns(foreignKey = @ForeignKey(name = "composite_fk"), value = {
@JoinColumn(name = "composite_id1", referencedColumnName = "id1"),
@JoinColumn(name = "composite_id2", referencedColumnName = "id2") })
@org.hibernate.annotations.ForeignKey(name = "composite_fk")
private Composite composite;
}
source to share