Hibernate(JPA)抽象超类的继承映射

22 浏览
0 Comments

Hibernate(JPA)抽象超类的继承映射

我的数据模型代表了法律实体,比如企业或个人。它们都是纳税实体,都有一个税号、一组电话号码和一组邮寄地址。

我有一个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注解,类似于以下代码:

@MappedSuperclass
public abstract class AbstractLegalEntity {
    private Long id;  // Getter注解为@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注解为@ManyToOne @JoinColumn private Long id; private String number; }

问题在于PhoneAddress对象需要引用它们的所有者,即AbstractLegalEntity。Hibernate报错:

@OneToOne或@ManyToOne在Phone中引用了未知实体:AbstractLegalEntity

这似乎是一个相当常见的Java继承情况,所以我希望Hibernate能支持它。我尝试根据一个Hibernate论坛问题更改AbstractLegalEntity的映射,不再使用@MappedSuperclass

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

然而,现在我遇到了以下错误。当我阅读关于这种继承映射类型的资料时,看起来我必须使用SEQUENCE而不是IDENTITY,而MySQL不支持SEQUENCE。

无法在映射中使用identity列键生成:ConcreteBusinessEntity

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

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

我认为我应该继续这条路线。我担心的是我将它映射为一个@Entity,而我实际上从不希望AbstractLegalEntity的实例存在。我想知道这是否是正确的方法。在这种情况下,我应该采取什么正确的方法?

0