从数据库中选择MappedSuperclass(Hibernate)

pek*_*pek 10 java hibernate

问题

我有一个@MappedSuperclass名为Data的数据作为我数据库中每个实体的父级.它包含像Id等公共属性.然后我有一个扩展Data的实体,这也是@MappedSuperclass由于它的子类的共同功能.我的数据库中的映射是正确的.

这是我的层次结构的一个例子

@MappedSuperclass
Data  
 |  @MappedSuperclass
 +- Employee  
 |      |  @Entity
 |      +- FullTimeEmployee
 |      |  @Entity
 |      +- PartTimeEmployee
 |  @Entity
 +- Store

并且表格已正确映射:

FullTimeEmployee  
PartTimeEmployee  
Store

无论如何都要查询数据库中所有Employee子类(FullTimeEmployee,PartTimeEmployee)作为Employee的实例而不引用查询中的子类名称?

就像是

List<Employee> allEmployees = getAllEmployees();
Run Code Online (Sandbox Code Playgroud)

我的想法是每当我决定创建另一个Employee子类(即AllDayEmployee)时,我就不必更改查询以包含名称.


因此,正如格雷戈里正确指出的那样,这是不可能的@MappedSuperclass.所以我将其更改为@Entity,因为我想为我使用的每个子类保留一个表InheritanceType.JOINED.

所以现在是上面的层次结构

@MappedSuperclass
Data  
 |  @Entity
 |  @Inheritance(strategy=InheritanceType.JOINED)
 +- Employee  
 |      |  @Entity
 |      +- FullTimeEmployee
 |      |  @Entity
 |      +- PartTimeEmployee
 |  @Entity
 +- Store

表格仍然是:

FullTimeEmployee  
PartTimeEmployee  
Store

现在,为了得到所有员工,我只需致电:

entityManager.createQuery("from Employee").getResultList();
Run Code Online (Sandbox Code Playgroud)

Gre*_*zky 8

不,如果您使用的是@MappedSuperclass

这样做的原因是,当您将基类定义为@MappedSuperclass时,没有为基类生成表,而是在具体表中复制所有属性.在您的示例中,仅存在FullTimeEmployee,PartTimeEmployee和Store表.

如果您希望能够查询基类实体,则需要为基类选择不同的映射.在基类上使用@Inheritance注释,并选择3种可能的映射策略之一 - SINGLE TABLE,TABLE PER CLASS或JOINED