Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override the Foreign Key Name pointing to Composite Key JPA/Hibernate

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;
}
like image 968
jchips12 Avatar asked Jul 14 '17 17:07

jchips12


1 Answers

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;
}
like image 85
Babl Avatar answered Oct 20 '22 04:10

Babl