覆盖指向复合键 JPA/Hibernate 的外键名称

jch*_*s12 5 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
Run Code Online (Sandbox Code Playgroud)

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

Hibernate: alter table my_entity add constraint FKms12cl9ma3dk8egqok1dasnfq foreign key (composite_id1, composite_id2) references composite
Run Code Online (Sandbox Code Playgroud)

我的代码有什么问题?我也试过了@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;
}
Run Code Online (Sandbox Code Playgroud)

Bab*_*abl 6

这是Hibernate 的一个已知问题,已在 5.2.8 版中修复

所以有两种方法可以修复它:要么将 Hibernate 更新到 5.2.8 版,要么通过添加

<hibernate.version>5.2.10.Final</hibernate.version>
Run Code Online (Sandbox Code Playgroud)

到您的 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;
}
Run Code Online (Sandbox Code Playgroud)