[英]Embeddable abstract class with JPA (+Hibernate)
I am trying to implement this JPA model: 我正在尝试实现这个JPA模型:
Owner
is an Entity
. 类Owner
是Entity
。 It has @Embedded
instance of class AbstractParent
. 它有@Embedded
类AbstractParent
实例。 AbstractParent
is @Embeddable
. AbstractParent
类是@Embeddable
。 It is an abstract class, and this class has two children.The children are concrete classes. 它是一个抽象类,这个类有两个孩子。孩子是具体的类。 The exception is: Cannot instantiate abstract class or interface: AbstractParent
例外是: Cannot instantiate abstract class or interface: AbstractParent
It seems that (1) I need component inheritance, but (2) component inheritance is not allowed in JPA and (3) it was not implemented in Hibernate. 似乎(1)我需要组件继承,但(2)JPA中不允许组件继承,(3)它没有在Hibernate中实现。 Could you confirm that (1), (2) and (3) are correct? 你能否证实(1),(2)和(3)是正确的? If they are correct could you provide any advice or workaround? 如果他们是正确的,您可以提供任何建议或解决方法吗? I use hibernate-jpa 2.0, hibernate-core 3.5.1, hibernate-core-annotations 3.2.0 我使用hibernate-jpa 2.0,hibernate-core 3.5.1,hibernate-core-annotations 3.2.0
To answer questions why one may need this implementation: here is an example. 要回答问题,为什么需要这个实现:这是一个例子。 Database table has information about computers, computers have monitors, if monitor is LCD then it's parameter is "pixels". 数据库表有关于计算机的信息,计算机有监视器,如果监视器是LCD,那么它的参数是“像素”。 If monitor is a TV then it's parameter is "lines". 如果显示器是电视,那么它的参数是“线”。 All monitors also have parameter "weight" Data structure of this table includes: id, RAM, monitor_indicator, weight, lines, pixels. 所有监视器也有参数“weight”这个表的数据结构包括:id,RAM,monitor_indicator,weight,lines,pixels。
This data structure can be implemented in classes: 这个数据结构可以在类中实现:
Computer
{id, RAM, display} 类Computer
{id,RAM,display}
AbstractDisplay
{weight} 抽象类AbstractDisplay
{weight}
LCDDisplay
{pixels} inherits class AbstractDisplay
类LCDDisplay
{pixels}继承AbstractDisplay
类
TVDisplay
{lines} inherits class AbstractDisplay
TVDisplay
{lines}类继承AbstractDisplay
类
The basic idea is that main class (Owner/Computer) embeds another class (Parent/AbstractDisplay) that can have different set of parameters depending on type of the embedded class. 基本思想是主类(所有者/计算机)嵌入另一个类(Parent / AbstractDisplay),该类可以根据嵌入类的类型具有不同的参数集。
Regarding how embedded abstract class can be instantiated: same way as an abstract class is instantiated now in JPA: in the above example "monitor_indicator" indicates children class that should be used, this field must exist during the time when class Computer is instantiated. 关于如何实例化嵌入式抽象类:与现在在JPA中实例化抽象类的方式相同:在上面的示例中,“monitor_indicator”表示应该使用的子类,该字段必须在实例化类Computer时存在。
Embedding an Abstract
class doesn't make any logical sense, it can't be instantiated if it is Abstract
. 嵌入Abstract
类没有任何逻辑意义,如果它是Abstract
,则无法实例化。 You need to re-work your logic on why you think you need to embed an Abstract
class and not a specific implementation. 您需要重新设置逻辑,以了解为什么您认为需要嵌入Abstract
类而不是特定的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.