TL; DR如何强制执行Hibernate模式创建以在每个具体类的表设置中创建外键约束AbstractProperty.ownerId
到Owner.ownerId
为下面显示的结构,而不需要将Owner
属性添加到AbstractProperty
?在一对一每个具体类结构中创建外键
我正在一个项目,我有下面的类结构:
的Owner
具有一一对一映射到一个AbstractProperty
,这是由ConcreteProperty
类扩展(和其他人一样AnotherProperty
,但这不是真正相关的问题的其余部分)。
AbstractProperty
确实只有一个属性abstractPropertyId
。因此,我们希望使用table-per-concrete-class结构,最终以表Owner
,ConcreteProperty
和其他AbstractProperty
扩展类(AnotherProperty
)的表格结束。
为此,我创建了以下映射Owner
:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example">
<class name="Owner">
<id name="ownerId">
<generator class="identity"/>
</id>
<property name="ownerProperty"/>
<one-to-one name="abstractProperty"/>
</class>
</hibernate-mapping>
而对于AbstractProperty
:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example">
<class name="AbstractProperty" abstract="true">
<id name="ownerId">
<generator class="foreign">
<param name="property">ownerId</param>
</generator>
</id>
<union-subclass name="ConcreteProperty">
<property name="concreteProperty"/>
</union-subclass>
<union-subclass name="AnotherProperty">
<property name="anotherProperty"/>
</union-subclass>
</class>
</hibernate-mapping>
这工作。
然而,这里是我的问题,使用此映射和Hibernate来创建模式,我(<property name="hbm2ddl.auto">create</property>
),它不会创建从ConcreteProperty.ownerId
数据库字段外键约束的Owner.ownerId
领域。它,当我创建使用此映射AbstractProperty
(其中owner
字段为Owner
类型的在AbstractProperty
java类)的逆约束一对一个字段从AbstractProperty
到Owner
:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example">
<class name="AbstractProperty" abstract="true">
<id name="ownerId">
<generator class="foreign">
<param name="property">ownerId</param>
</generator>
</id>
<one-to-one name="owner" constrained="true"/>
<union-subclass name="ConcreteProperty">
<property name="concreteProperty"/>
</union-subclass>
<union-subclass name="AnotherProperty">
<property name="anotherProperty"/>
</union-subclass>
</class>
</hibernate-mapping>
我怎样才能在我的AbstractProperty
没有这个Owner
字段时,强制创建从AbstractProperty.ownerId
到Owner.ownerId
的外键?
你为什么期望/需要从'* Property'表到'Owner'表有一个DB列/引用?根据你的方案,我会说在数据库中唯一的参考瓦特/外键是从'所有者'表格*属性... –
我不能从'所有者'设置一个外键到'abstractPropertyId',因为我wouldn不知道它引用了哪个表(即哪个'AbstractProperty'实现)。 – drvdijk
不是一个实际的答案,而是一个关于Why-What-How谱系的“为什么”的问题:您是否明确构建了一个实体 - 属性 - 值模型? –