有没有办法在JPA的实体的子类中覆盖ID? [英] Is there a way to override ID in an entity's subclass in JPA?

查看:224
本文介绍了有没有办法在JPA的实体的子类中覆盖ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不使用抽象基类(或超类)的特定要求下,我需要实现两个实体的简单层次结构,其中一个实体应该扩展另一个实体,但它们有不同的@Id。

我对此的搜索似乎认为这是不可能的,或者只是因为我使用映射的超类(由于某个策略而禁止在我的情况下)。

我不想复制具有几十个属性的实体代码,然后通过添加/覆盖属性来改变重复项以避免将来的维护问题,但那么我被卡在JPA限制。



任何帮助/建议将不胜感激。

解决方案

id 类型的非抽象派生实体与JPA继承策略不兼容。



我的意思是:



想象一下,你已经成功了,层次结构中的不同类为 id 使用了不同的不兼容类型。




  • 在这种情况下,如何定义单个表继承的DB约束?

  • 和加入的继承?



编辑:当涉及到id定义时,JPA不区分继承策略。你甚至不能确定你可以在纯JPA中使用 TABLE_PER_CLASS 。几乎所有的提供者都实现它,但它被指定为可选的,因此是可移植性最低的继承策略。

但问题仍然存在。数据库约束如何才能使表可以由持久性提供者明确地使用?例如。哪些列应该包含数据库级别的主键?



如果您无法使父级实体既不是抽象的,也不是可嵌入的,也不是使用相同的ID,您必须解决该问题。你如何做到这一点高度依赖于你想达到什么以及你有什么组织限制。

有几种可能性 - B中的一个字段,有效地创建一个1-1关系。



更丑陋的方法可能是本地和构造函数查询,但我怀疑你想要下降到那么远。 strong> tl; dr 不,这是不可能的。


Under a specific requirement such as not using an abstract base class (or super class), I need to implement a simple hierarchy of two entities one of which is supposed to extend the other but have a different @Id of its own.

My googling about this seems to conclude this is impossible or only on condition that I use a mapped super class (which is forbidden in my case due to a certain policy).

I don't want to duplicate the code of the entity with several dozen attributes and then mutate the duplicate by adding / overriding attributes in order to avoid future maintenance problems, but then I'm stuck in JPA restrictions.

Any help / suggestion will be appreciated.

解决方案

Having different id types for non-abstract derived entities is not compatible with the JPA inheritance strategies.

What I mean is:

Imagine you have succeeded and different classes in the hierarchy use different incompatible types for the id.

  • how would you define the DB constraints for a single table inheritance in such a case?
  • and for joined inheritance?

EDIT: JPA does not distinguish between inheritance strategies when it comes to id definition. And you cannot even be sure that you can use TABLE_PER_CLASS with pure JPA. Virtually all providers implement it, but it is specified as optional and thus the least portable inheritance strategy.

The question remains however. How can the DB constraints look in order to make the table usable unambiguously by the persistence provider? E.g. Which columns should comprise the primary key on DB level?

If you cannot make the parent entity neither abstract nor embeddable nor use the same id, you will have to work around that. How you do that is highly dependant on what you want to achieve and what organizational constraints you have.

There are several possibilities - the least invasive would be composition, having A as a field in B, effectively creating a 1-1 relation.

More ugly approaches could be native and constructor queries but I doubt you want to descend that far.

tl;dr No, it is not possible.

这篇关于有没有办法在JPA的实体的子类中覆盖ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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