Hibernate(JPA)inheritance抽象超类的映射

我的数据模型代表法律实体,例如商业或个人。 两者都是纳税实体,都有TaxID,电话号码集和邮寄地址集合。

我有一个Java模型,它有两个扩展抽象类的具体类。 抽象类具有两个具体类共有的属性和集合。

AbstractLegalEntity ConcreteBusinessEntity ConcretePersonEntity ------------------- ---------------------- -------------------- Set phones String name String first Set
addresses BusinessType type String last String taxId String middle Address Phone ------- ----- AbsractLegalEntity owner AbstractLegalEntity owner String street1 String number String street2 String city String state String zip

我在MySQL数据库上使用Hibernate JPA Annotations ,其类如下所示:

 @MappedSuperclass public abstract class AbstractLegalEntity { private Long id; // Getter annotated with @Id @Generated private Set phones = new HashSet(); // @OneToMany private Set
address = new HashSet
(); // @OneToMany private String taxId; } @Entity public class ConcretePersonEntity extends AbstractLegalEntity { private String first; private String last; private String middle; } @Entity public class Phone { private AbstractLegalEntity owner; // Getter annotated @ManyToOne @JoinColumn private Long id; private String number; }

问题是PhoneAddress对象需要引用它们的所有者,这是一个AbstractLegalEntity 。 Hibernate抱怨:

 @OneToOne or @ManyToOne on Phone references an unknown entity: AbstractLegalEntity 

看起来这将是一个相当常见的Javainheritance场景,所以我希望Hibernate会支持它。 我已经尝试根据Hibernate论坛问题更改AbstractLegalEntity的映射,不再使用@MappedSuperclass

 @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 

但是,现在我收到以下错误。 在阅读这种inheritance映射类型时,看起来我必须使用SEQUENCE而不是IDENTITY,并且MySQL不支持SEQUENCE。

 Cannot use identity column key generation with  mapping for: ConcreteBusinessEntity 

当我使用以下映射时,我在使事情工作方面取得了更多进展。

 @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn( name="entitytype", discriminatorType=DiscriminatorType.STRING ) 

我想我应该继续走这条路。 我担心的是,当我真的不希望AbstractLegalEntity的实例存在时,我将它映射为@Entity 。 我想知道这是否是正确的方法。 对于这种情况,我应该采取什么样的正确方法?

使用:

 @Entity @Inheritance(strategy = InheritanceType.JOINED) AbstractLegalEntity 

然后在数据库中,您将拥有一个用于AbstractLegalEntity的表和用于扩展AbstractLegalEntity类的类的表。 如果它是抽象的,你将不会有AbstractLegalEntity的实例。 可以使用多态性。

当你使用:

 @MappedSuperclass AbstractLegalEntity @Entity ConcretePersonEntity extends AbstractLegalEntity 

它在数据库中只创建一个表ConcretePersonEntity,但是包含两个类的列。

@Entity注释添加到AbstractLegalEntityAbstractLegalEntity实例永远不会存在 – hibernate将根据Id字段加载适当的扩展实例 – ConcreteBusinessEntityConcretePersonEntity

您必须将AbstracLegalEntity声明为@Entity 。 即使使用@Entity注释,您的类仍然是抽象的。 因此,您将只有具体子类的实例。