gpt4 book ai didi

java - 从数据库中选择 MappedSuperclass (Hibernate)

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:58:16 24 4
gpt4 key购买 nike

问题

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

这是我的层次结构的例子

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

And the tables are correctly mapped:

FullTimeEmployee  PartTimeEmployee  Store

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),我都不必更改查询以包含名称。


解决方案

所以,作为Gregory正确地指出,这对于 @MappedSuperclass 是不可能的。所以我将其更改为@Entity,并且因为我想为每个子类保留一个表,所以我使用了 InheritanceType.JOINED

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

@MappedSuperclassData   |  @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

原因是当您将基类定义为@MappedSuperclass 时,没有为基类生成表,而是所有属性都复制到具体表中。在您的示例中,将只存在 FullTimeEmployee、PartTimeEmployee 和 Store 表。

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

关于java - 从数据库中选择 MappedSuperclass (Hibernate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1427439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com