重写指向复合键jpa/hibernate的外键名

szqfcxe2  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(246)

我正在使用springboot1.5.4和springdatajpa,并且我正在尝试在这个过程中覆盖自动生成的外键名 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;
}
nwo49xxi

nwo49xxi1#

这是5.2.8版本中修复的hibernate的已知问题
所以有两种方法可以解决这个问题:要么将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;
}

相关问题