问题描述
我的数据库中的每个实体都有一个名为Data的 @MappedSuperclass
。它包含像Id等常见属性。然后,我有一个实体,它扩展了Data,它也是一个 @MappedSuperclass
,这是由于它的子类的通用功能。我的数据库中的映射是正确的。
I have a @MappedSuperclass
called Data as the parent of every Entity in my database. It contains common attributes like Id etc. I then have an entity that extends Data which is also a @MappedSuperclass
due to common functionality of its subclasses. The mapping in my database is correct.
以下是我的层次结构示例
Here is an example of my hierarchy
@MappedSuperclass
Data
| @MappedSuperclass
+- Employee
| | @Entity
| +- FullTimeEmployee
| | @Entity
| +- PartTimeEmployee
| @Entity
+- Store
表格正确映射:
And the tables are correctly mapped:
FullTimeEmployee
PartTimeEmployee
Store
有没有办法查询数据库对于所有Employee子类(FullTimeEmployee,PartTimeEmployee)作为Employee的实例而不引用查询中的子类名称?
Is there anyway to query the database for all Employee subclasses (FullTimeEmployee, PartTimeEmployee) as instances of Employee without referring the name of the subclasses in the query?
类似于
Something like
List<Employee> allEmployees = getAllEmployees();
这个想法是每当我决定创建Employee的另一个子类(即AllDayEmployee)时,我不会有更改查询以包含名称。
The idea is that whenever I decide to create another subclass of Employee (i.e. AllDayEmployee) I will not have to change the query to include the name.
因此,正如正确指出的那样,这不是可能用 @MappedSuperclass
。所以我将它改为@Entity,因为我想为每个子类保留一个表,我使用了 InheritanceType.JOINED
。
So, as Gregory correctly pointed out, this is not possible with @MappedSuperclass
. So I changed it into @Entity and, since I wanted to preserve a table for each subclass I used InheritanceType.JOINED
.
因此,上面的层次结构现在是
So the above hierarchy is now
@MappedSuperclass
Data
| @Entity
| @Inheritance(strategy=InheritanceType.JOINED)
+- Employee
| | @Entity
| +- FullTimeEmployee
| | @Entity
| +- PartTimeEmployee
| @Entity
+- Store
表格仍然是:
And the tables are still:
FullTimeEmployee
PartTimeEmployee
Store
现在,为了让所有员工只需调用:
So now, to get all Employees I simply call:
entityManager.createQuery("from Employee").getResultList();
推荐答案
否,如果您使用@MappedSuperclass
No if you are using @MappedSuperclass
其原因是,当您将基类定义为@MappedSuperclass时,没有为基类生成表,而是将所有属性复制到具体表中。在您的示例中,只有FullTimeEmployee,PartTimeEmployee和Store表存在。
The reason for this is that when you define base class as @MappedSuperclass, there is no table generated for the base class, instead all of the properties are replicated in the concrete tables. In your example only FullTimeEmployee, PartTimeEmployee and Store tables would exist.
如果您希望能够查询基类实体,则需要为基类选择不同的映射。在基类上使用@Inheritance注释并选择3种可能的映射策略之一 - SINGLE TABLE,TABLE PER CLASS或JOINED
If you want to be able to query for base class entities you need to select different mapping for base classes. Use @Inheritance annotation on the base class and select one of the 3 possible mapping strategies - SINGLE TABLE, TABLE PER CLASS or JOINED
这篇关于从数据库中选择MappedSuperclass(Hibernate)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!