2017-07-14 78 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; 
}