覆盖指向Composite Key JPA / Hibernate的外键名称

时间:2017-07-14 17:19:34

标签: java hibernate jpa spring-boot

我使用spring-boot 1.5.4和spring-data-jpa,我试图在spring.jpa.hibernate.ddl-auto=create期间覆盖自动生成的外键名称。

对于简单ID,我可以覆盖它:simple_fk

Hibernate: alter table my_entity add constraint simple_fk foreign key (simple_id) references simple

但不适用于具有复合ID的外键:FKms12cl9ma3dk8egqok1dasnfq

Hibernate: alter table my_entity add constraint FKms12cl9ma3dk8egqok1dasnfq foreign key (composite_id1, composite_id2) references composite

我的代码出了什么问题?我也试过了@PrimaryKeyJoinColumn

请参阅下面的课程定义。

@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;
}

1 个答案:

答案 0 :(得分:4)

这是带有Hibernate的known issue,在5.2.8版本中修复了

所以有两种方法可以解决它:你可以通过添加

将Hibernate更新到5.2.8或更高版本
<hibernate.version>5.2.10.Final</hibernate.version>

到你的pom.xml,它基本上会将Hibernate更新到最新版本。

或者如果无法进行Hibernate更新或风险太大,您可以添加旧版/弃用@org.hibernate.annotations.ForeignKey(name = "composite_fk")注释 composite字段会使您的代码看起来像

@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;
}