且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Hibernate EntityManager获取映射的超类的实例

更新时间:2022-04-17 08:43:25

一个

A mapped superclass isn't an entity. It's only a class that shares its mapping definition with its subclasses. You, therefore, can't select it with Hibernate or any other JPA implementation.

如果要在查询中选择超类或定义多态关联,则应查看

If you want to select the superclass in a query or define polymorphic associations, you should look at the table per class strategy. It maps each concrete entity class to its own database table. You can set that strategy by annotating your superclass with @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS), e.g.:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Manufacturer { ... }


@Entity
public class Product extends Manufacturer { ...}

在下一步中,您需要确定您的超类是否应该是抽象的.使用每个类的表策略,可以使您的超类抽象化.这样,您将无法实例化和保留该类的任何对象.但是您可以在查询和关联映射中使用它们.然后,Hibernate总是返回特定的子类.

In the next step, you need to decide if your superclass shall be abstract or not. Using the table per class strategy, you can make your superclass abstract. You will then not be able to instantiate and persist any objects of that class. But you can use them in your queries and association mappings. Hibernate then always returns the specific subclass.

您写道,您希望使超类抽象化,而在您的一个应用程序中没有任何具体的子类.这听起来像是一个有问题的设计决策,因为您将无法在该应用程序中使用超类.Hibernate不会知道任何子类,因此您将无法选择或持久化它们.

You wrote that you would prefer to make the superclass abstract without having any concrete subclasses in one of your applications. That sounds like a questionable design decision because you wouldn't be able to use the superclass in that application. Hibernate wouldn't know any of the subclasses, and you wouldn't be able to select or persist them.

如果您想了解有关JPA映射继承层次结构的不同选项的更多信息,建议您阅读有关它的深入指南:

If you want to learn more about JPA's different options to map inheritance hierarchies, I recommend reading my in-depth guide about it: Inheritance Strategies with JPA and Hibernate – The Complete Guide