【发布时间】:2023-03-03 01:50:01
【问题描述】:
TL;DR 如何强制创建 Hibernate 模式,以在从 AbstractProperty.ownerId 到 Owner.ownerId 的每个具体类的表设置中为下面显示的结构创建外键约束,而不向AbstractProperty 添加Owner 属性?
我正在从事一个具有以下类结构的项目:
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 的此映射创建从AbstractProperty 到Owner 的反向约束一对一字段时(其中owner 字段在AbstractProperty java 类中的类型为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 中带外键的唯一引用是从Owner表到 *Property... -
我无法设置从
Owner到abstractPropertyId的外键,因为我不知道它引用了哪个表(即哪个AbstractProperty实现)。 -
不是一个实际的答案,而是一个关于Why-What-How 范围内“为什么”的问题:您是否明确构建了一个实体-属性-值模型?
-
@drvdijk,我们已经实现了类似的东西,如果没有这个
在 Abstractproperty.hbm 中,就无法创建它.xml。我查看了我们 4-5 年前的代码,这正是我们所做的。