2017-07-14 106 views
3

我正在使用spring-boot-1.5.4和spring-data-jpa,我試圖在spring.jpa.hibernate.ddl-auto=create期間覆蓋自動生成的外鍵名稱。覆蓋指向複合鍵的外鍵名稱JPA/Hibernate

對於簡單的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

這是known issue與Hibernate能夠在版本5.2.8修復

因此,有兩種方法來解決這個問題:要麼你加入更新的Hibernate的版本5.2.8或向上

<hibernate.version>5.2.10.Final</hibernate.version> 

到您的pom.xml,它基本上會將Hibernate更新到最新版本。

,或者休眠更新是不可能的,或者是太冒險,你可以添加傳統的/不推薦您 composite@org.hibernate.annotations.ForeignKey(name = "composite_fk")註釋這將使你的代碼看起來像

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