I'm using spring-boot 1.5.4 with spring-data-jpa and I'm trying to override the auto generated foreign key name during spring.jpa.hibernate.ddl-auto=create
.
For 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 foreign key with composite id: FKms12cl9ma3dk8egqok1dasnfq
Hibernate: alter table my_entity add constraint FKms12cl9ma3dk8egqok1dasnfq foreign key (composite_id1, composite_id2) references composite
What is wrong with my code? I also tried @PrimaryKeyJoinColumn
.
Please see the 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;
}
This is a known issue with the Hibernate which was fix in version 5.2.8
So there are two ways to fix it: Either you update the Hibernate to the version 5.2.8 or up by adding
<hibernate.version>5.2.10.Final</hibernate.version>
to your pom.xml, which basically will update the Hibernate to the latest version.
or if Hibernate update is not possible or is just too risky you can add legacy/deprecated @org.hibernate.annotations.ForeignKey(name = "composite_fk")
annotation on your
composite
field which will make you 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With