我尝试用hibernate 5.2实现单表继承。 基类
Add(Stack)
作者类扩展了PropertyOwner:
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type", discriminatorType= DiscriminatorType.STRING)
@DiscriminatorValue("HAKSAHIBI")
@DiscriminatorOptions(force=true)
public class PropertyOwner implements implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
long id;
@ManyToOne
Property property;
@ManyToOne
Person person;
}
Composer类扩展了PropertyOwner:
@Entity
@DiscriminatorValue("AUTHOR")
class Author extends PropertyOwner {
}
人类:
@Entity
@DiscriminatorValue("COMPOSER")
class Composer extends PropertyOwner {
}
属性类
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
long id;
String title;
}
我期待表结构如下:
public class Property{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
long id;
String title;
@OneToMany
Set<Composer> composers = new HashSet<Composer>();
@OneToMany
Set<Author> authors = new HashSet<Author>();
}
但不幸的是,它为Author和Composer类创建了另一个表,其中包含以下语句
CREATE TABLE `Property` (
`id` bigint(20) NOT NULL,
`title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `Person` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `PropertyOwner` (
`type` varchar(31) NOT NULL,
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`property_id` bigint(20) DEFAULT NULL,
`person_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK77apjkkl14xwe45rs1ocgtt4u` (`property_id`),
KEY `FKqagfofgupovfly26enivfhm3j` (`person_id`),
CONSTRAINT `FK77apjkkl14xwe45rs1ocgtt4u` FOREIGN KEY (`property_id`) REFERENCES `property` (`id`),
CONSTRAINT `FKqagfofgupovfly26enivfhm3j` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
我做错了什么?我期望不应该创建property_PropertyOwner表,并且作者,Composer类信息应该保存在propertyOwner表中。
注意:我尝试了Enumarated注释,但这次在Property类中我无法定义Setauthor字段,我必须定义Set并向该对象添加枚举信息。 提前致谢 。
答案 0 :(得分:1)
在您的属性实体中具有多个子类(Composers和authors)的多个关联是没有意义的。因为您具有单个表继承,即您的属性所有者表将具有property_id的外键。 相反,您可以进行单一关联。
@OneToMany
Set<PropertyOwner> composers = new HashSet<PropertyOwner>();
您可以使用DiscriminatorColumn类型将此集合拆分为内存中的authors和composer。