使用TABLE_PER_CLASS继承策略时如何继承@ForeignKey设置

时间:2017-01-28 10:52:19

标签: jpa orm foreign-keys hibernate-5.x

我尝试使用@ForeignKey注释控制外键名称生成。这通常很有效。但在特殊情况下,它不是我想要的,我不知道如何配置它。

特殊情况是我使用@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)时。当基类具有@ManyToOne关系并且我想使用@ForeignKey指定外键名称时,它仅适用于基类。

         +------------+           +--------------+
         | BaseEntity |   ----->  | OtherEntity  |
         +------------+           +--------------+
                ^
                |
       +--------+---------+
  +----------+      +----------+
  |SubEntity1|      |SubEntity2|
  +----------+      +----------+

我的BaseEntity

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "base_entity")
public class BaseEntity {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    @JoinColumn(foreignKey = @ForeignKey(name = "FK_other_entity"))
    private OtherEntity otherEntity;
}

我的SubEntity1(与SubEntity2相同)

@Entity
@Table(name = "sub_entity_1")
public class SubEntity1 extends BaseEntity {
}

只是为了完成.... OtherEntity

@Entity
@Table(name = "other_entity")
public class OtherEntity {
    @Id
    @GeneratedValue
    private Long id;
}

Hibernate将生成一个包含以下外键定义的ddl脚本:

alter table base_entity 
   add constraint FK_other_entity 
   foreign key (otherEntity_id) 
   references other_entity (id);

alter table sub_entity_1 
   add constraint FK_jtmdc6tiytduxbpesmng9g3bk 
   foreign key (otherEntity_id) 
   references other_entity (id);

alter table sub_entity_2 
   add constraint FK_9xpb6q7qeq5r3pq071cbbiygx 
   foreign key (otherEntity_id) 
   references other_entity (id);

如您所见,子实体的外键名称是随机的。

子实体没有包含对OtherEntity的引用的字段,因此我无法在其中放置@ForeignKey注释。

在每个类继承类型使用表时,如何控制子实体的外键名称?

我正在使用

  • spring-boot 1.4.3.RELEASE
  • hibernate 5.6.2.Final

修改

我也尝试使用@AssociationOverride,但它不起作用。

如果您需要快速设置架构生成,可能需要查看我之前的问题Generate DDL with spring boot using a custom delimiter

1 个答案:

答案 0 :(得分:0)

似乎是一个休眠错误

我已经投了这两个错误。也许你也想投票支持它,希望很快就会得到解决。

我将观察问题的变化,并在修复错误后更新此答案。

我的"现在的解决方案" 是使用InheritanceType.JOINED

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "base_entity")
public class BaseEntity {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    @JoinColumn(foreignKey = @ForeignKey(name = "FK_other_entity"))
    private OtherEntity otherEntity;
}

并设置已连接表的外键

@Entity
@Table(name = "sub_entity_1")
@PrimaryKeyJoinColumn(foreignKey = @ForeignKey(name = "FK_base_entity"))
public class SubEntity1 extends BaseEntity {

}