Jpa 使用表\每\类继承策略时如何继承@ForeignKey设置
我尝试使用Jpa 使用表\每\类继承策略时如何继承@ForeignKey设置,jpa,orm,foreign-keys,hibernate-5.x,Jpa,Orm,Foreign Keys,Hibernate 5.x,我尝试使用@ForeignKey注释控制外键名称的生成。这通常效果很好。但在特殊情况下,它不是我想要的,我不知道如何配置它 特殊情况是当我使用@继承(strategy=InheritanceType.TABLE\u PER\u CLASS)时。当基类具有@ManyToOne关系并且我想使用@ForeignKey指定外键名称时,它只适用于基类 +------------+ +--------------+ | BaseEntity | -
@ForeignKey
注释控制外键名称的生成。这通常效果很好。但在特殊情况下,它不是我想要的,我不知道如何配置它
特殊情况是当我使用@继承(strategy=InheritanceType.TABLE\u PER\u 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;
}
我的子实体1
(与子实体2
相同)
只是为了完整。。。。其他实体
:
@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
注释
使用每个类继承类型的表时,如何控制子实体的外键名称?
我正在使用
- 弹簧靴1.4.3.1释放
- hibernate 5.6.2.1最终版本
如果您需要快速设置模式生成,您可能想看看我前面的问题似乎是一个hibernate错误
我的“目前解决方案”是使用
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 {
}
@Entity
@Table(name = "sub_entity_1")
@PrimaryKeyJoinColumn(foreignKey = @ForeignKey(name = "FK_base_entity"))
public class SubEntity1 extends BaseEntity {
}