我的数据模型代表法律实体,例如商家或个人。两者都是纳税实体,都有TaxID,电话号码集和邮寄地址集。
我有一个Java模型,它有两个扩展抽象类的具体类。抽象类具有两个具体类共有的属性和集合。
AbstractLegalEntity ConcreteBusinessEntity ConcretePersonEntity
------------------- ---------------------- --------------------
Set<Phone> phones String name String first
Set<Address> 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<Phone> phones = new HashSet<Phone>(); // @OneToMany
private Set<Address> address = new HashSet<Address>(); // @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;
}
问题是Phone
和Address
个对象需要引用其所有者,即AbstractLegalEntity
。 Hibernate抱怨:
@OneToOne or @ManyToOne on Phone references an unknown
entity: AbstractLegalEntity
这似乎是一个相当常见的Java继承场景,所以我希望Hibernate会支持它。我已尝试根据Hibernate forum question更改AbstractLegalEntity的映射,不再使用@MappedSuperclass
:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
但是,现在我收到以下错误。在阅读这种继承映射类型时,看起来我必须使用SEQUENCE而不是IDENTITY,并且MySQL不支持SEQUENCE。
Cannot use identity column key generation with <union-subclass>
mapping for: ConcreteBusinessEntity
当我使用以下映射时,我在使事情正常工作方面取得了更多进展。
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="entitytype",
discriminatorType=DiscriminatorType.STRING
)
我想我应该继续这条道路。我担心的是,当我真的不希望AbstractLegalEntity的实例存在时,我将它映射为@Entity
。我想知道这是否是正确的方法。对于这种情况,我应该采取什么样的正确方法?
答案 0 :(得分:41)
使用:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
AbstractLegalEntity
然后在数据库中,您将拥有一个用于AbstractLegalEntity的表和用于扩展AbstractLegalEntity类的类的表。如果它是抽象的,你将不会有AbstractLegalEntity的实例。可以使用多态性。
使用时:
@MappedSuperclass
AbstractLegalEntity
@Entity
ConcretePersonEntity extends AbstractLegalEntity
它在数据库中只创建一个表ConcretePersonEntity,但是包含两个类的列。
答案 1 :(得分:1)
将@Entity
注释添加到AbstractLegalEntity
。 AbstractLegalEntity
的实例永远不会存在 - hibernate将根据Id字段加载适当的扩展实例 - ConcreteBusinessEntity
或ConcretePersonEntity
。
答案 2 :(得分:1)
您必须将AbstracLegalEntity
声明为@Entity
。即使使用@Entity
注释,您的类仍然是抽象的。因此,您将只有具体子类的实例。