【问题标题】:Unusual Hibernate inheritance mapping不寻常的 Hibernate 继承映射
【发布时间】:2011-01-13 03:52:07
【问题描述】:

我有一个关于对象关系映射的奇怪谜题,使用 Java 和 Hibernate。

我们有一个看起来像这样的现有架构:

create table foo (id int8, /* ... */ primary key (id));
create table bar (id int8, foo int8, /* ... */ primary key (id));
alter table bar add constraint fk_foobar foreign key (foo) references foo;

通常,您会使用ManyToOne 关系映射它。

class Foo { /* ... */ }
class Bar { private Foo foo; /* ... */ }

但我团队中的一个人想要将其映射为继承关系:

class Foo { /* ... */ }
class Bar extends Foo { /* ... */ }

有什么方法可以用 Hibernate 解决这个问题?

编辑:重点是表bar有一个外键列foo,这与bar的标识列不同。

【问题讨论】:

  • 我在 C# 中使用 NHibernate(Hibernate 的端口),答案是肯定的。 NHibernate 文档中有一些示例,我确定 Hibernate 也存在同样的示例
  • 您的问题解决了吗?请提供反馈。
  • 我很确定答案是否定的。我敢打赌 Hibernate 是硬连线的,所以如果你有继承关系,派生类表中的主键必须是基类表的外键。

标签: java hibernate orm jpa mapping


【解决方案1】:

如果 Bar 是一个 Foo,你应该只将它映射为一个继承关系。否则,您应该使用组合。 但是,当然,我不知道上下文,所以我不知道将这些类映射为子类和基类是否正确。

无论如何,是的,有可能做到这一点。 检查the different possibilities to create an inheritance relationship in Hibernate.

例如,您可以在这里使用 Joined Subclass 场景:

<class name="Foo" table="Foos">
   <joined-subclass="Bar" table="Bars">
   </joined-subclass>
</class>

【讨论】:

  • 实际用例有点像灰色地带。 Bar 提供有关 Foo 的附加数据。这样,您可以将其视为 Bar is-a Foo。但是可能有多个对象提供关于同一个 Foo 的附加数据。这更倾向于 Bar has-a Foo。您提供的映射不会映射到现有架构。 bar 表有一个与 foo 外键列不同的 id 列。
  • 这对我来说是一个组合,因为它是一对多的。您不能使用继承为同一个 Foo 拥有多个 Bars。考虑一下所有“附加信息”对象的继承映射。
【解决方案2】:
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Foo { .. }

但只有在继承是逻辑时才这样做。 IE。如果是Dog extends Animal,则不是User extends Group

【讨论】:

    猜你喜欢
    • 2017-12-07
    • 2011-11-22
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多