【问题标题】:Mixing JOINED and SINGLE_TABLE Inheritence using Annotations使用注释混合 JOINED 和 SINGLE_TABLE 继承
【发布时间】:2013-02-25 18:58:27
【问题描述】:

我在论坛上查看过类似的问题,但没有找到任何可以解决我正在寻找的东西(至少我能说的)。

我有一种情况,我们有多个客户端,每个客户端都有多种请求类型。我试图完成的是有一个父表“请求”,它为每个客户端拆分成一个子表——“ClientARequest”、“ClientBRequest”。从那里,我将有多个类映射到同一个客户端表。 “ClientARequest1”和“ClientARequest2”都映射到“ClientARequest”,对于ClientB也是如此。我可以让第一部分工作与 JOINED 继承没有问题。我可以让第二个工作以及保存。但是,在获取时,hibernate 正在创建最后一个映射类的实例,因此根据我如何使用获取的对象,我会得到一个 ClassCastException 或者我不会有正确的数据,因为它是错误的类。

@Entity(name="Request")
@Table(name = "REQUEST")
@Inheritance(strategy=InheritanceType.JOINED)  
@DiscriminatorColumn(name="MY_TYPE", discriminatorType=DiscriminatorType.STRING)
public class Request  { ... }

@Entity(name="ClientARequest1")
@Table(name = "CLIENTAREQUEST")
@DiscriminatorValue("ClientA")
public class ClientARequest1 extends Request { ... }

@Entity(name="ClientARequest2")
@Table(name = "CLIENTAREQUEST")
@DiscriminatorValue("ClientA")
public class ClientARequest2 extends Request { ... }

ClientB 也一样:

@Entity(name="ClientBRequest1")
@Table(name = "CLIENTBREQUEST")
@DiscriminatorValue("ClientB")
public class ClientBRequest1 extends Request { ... }

@Entity(name="ClientBRequest2")
@Table(name = "CLIENTBREQUEST")
@DiscriminatorValue("ClientB")
public class ClientBRequest2 extends Request { ... }

所以,就像我提到的那样,创建了三个表,Request、ClientARequest 和 ClientBRequest,这在表之间进行区分是没有问题的。当尝试从表中获取数据时,hibernate 使用第二个映射来创建类的实例。

例如

ClientARequest1 r = new ClientARequest1("ClientA");
dao.save(r);

按预期工作。
但是对于:

Request r = (Request) dao.findById(1l);  //where id==1 is a ClientARequest1

实际上会拉回一个 ClientARequest2。

任何想法将不胜感激。这个解决方案不可行吗,有没有办法将表格分解到另一个级别?

2/26/13 美国东部标准时间上午 11:19:
我在这个线程How to mix inheritance strategies with JPA annotations and Hibernate? 中尝试了解决方案,但我无法正确映射子类 BB1、BB2、CC1、CC2,因为它们的属性将放置在基父表 A 中。我希望它们的属性放置分别在它们的直接父表 BB、CC 中。

【问题讨论】:

    标签: hibernate inheritance annotations mixed


    【解决方案1】:

    我明白了。我遵循了How to mix inheritance strategies with JPA annotations and Hibernate? 中的解决方案。我唯一改变的是将@MappedSuperclass 添加到BB、CC 级别,并将@Entity 和@SecondaryTable 移动到BB1、BB2、CC1、CC2 级别。

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 2012-04-11
      • 2011-08-05
      • 2011-11-12
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      相关资源
      最近更新 更多