JPA:实现模型层次结构 - @MappedSuperclass 与 @Inheritance [英] JPA: Implementing Model Hierarchy - @MappedSuperclass vs. @Inheritance

查看:19
本文介绍了JPA:实现模型层次结构 - @MappedSuperclass 与 @Inheritance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有 PostgreSQLJPA 的 Play Framework 1.2.4.我想要一个模型层次结构,并看到有一些替代方法可以做到这一点.

I am using Play Framework 1.2.4 with PostgreSQL and JPA. I would like to have a Model hierarchy and see that there are some alternatives to doing this.

我有一个基类(它是抽象的)和两个扩展这个基类的具体类.我不想保留这个基类,而我想拥有具体的类.在基类中,我有另一个模型类作为属性,换句话说,我的基类中有 @ManyToOne 关系.

I have a base class (which is abstract) and two concrete classes extending this base class. I don't want to persist this base class while I want to have concrete classes. In the base class, I have another Model classes as properties, in other words, I have @ManyToOne relationships in my base class.

我的问题是实现此目的的最佳方法是什么?使用 @MappedSuperclass@InheritanceTABLE_PER_CLASS 策略?我有点困惑,因为它们看起来几乎等效.

My question is what is the best way of implementing this? Using @MappedSuperclass or @Inheritance with TABLE_PER_CLASS strategy? I am a bit confused as they seem virtually equivalent.

我也担心将来可能会遇到的查询和性能问题.

I also have some concerns about querying and performance issues that I might face in future.

推荐答案

MappedSuperClass 必须用于继承属性、关联和方法.

MappedSuperClass must be used to inherit properties, associations, and methods.

当您有一个实体和多个子实体时,必须使用实体继承.

Entity inheritance must be used when you have an entity, and several sub-entities.

您可以通过回答以下问题来判断您是否需要一个或另一个:模型中是否有其他实体可以与基类关联?

You can tell if you need one or the other by answering this questions: is there some other entity in the model which could have an association with the base class?

如果是,那么基类实际上是一个实体,应该使用实体继承.如果不是,则基类实际上是一个包含多个不相关实体共有的属性和方法的类,您应该使用映射的超类.

If yes, then the base class is in fact an entity, and you should use entity inheritance. If no, then the base class is in fact a class that contains attributes and methods that are common to several unrelated entities, and you should use a mapped superclass.

例如:

  • 您可以收到多种消息:短信、电子邮件或电话消息.一个人有一个消息列表.无论消息类型如何,您还可以将提醒链接到消息.在这种情况下,Message 显然是一个实体,必须使用实体继承.
  • 您所有的域对象都可以有创建日期、修改日期和 ID,因此您可以使它们从基础 AbstractDomainObject 类继承.但是任何实体都不会与 AbstractDomainObject 有关联.它始终是与更具体实体的关联:客户、公司等等.在这种情况下,使用 MappedSuperClass 是有意义的.

这篇关于JPA:实现模型层次结构 - @MappedSuperclass 与 @Inheritance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆