Hibernate - 嵌入@Entity? [英] Hibernate - embedded @Entity?
问题描述
在我的用例中,我想在一个实体中 @Embedded
一个类 C
。
另一个实体引用 C
,其中 @OneToMany
关联因此 C
用 @Entity
注释。
我知道这看起来很糟糕的设计,但我相信它对我来说非常合适。
是否可以强制Hibernate嵌入实体?如果我尝试它,Hibernate会抱怨C的id属性缺失setter。
我认为问题来自于此:
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private长ID;
Hibernate不允许您将 Embeddable
作为实体
或嵌入实体
。根据 Hibernate类型:
- an
Embeddable
,没有标识符,因为它的状态是拥有实体
。 不能嵌入 - 和
实体,因为每个 实体
有一个独特的生命周期。
由于另一个类已经有一个 你可以做什么,就是在你想要嵌入 元素的实体中使用它作为 @OneToMany 关联到类
实体。您可以使该目标实体成为该关联的所有者,从而 C
,显然你不能把它变成 Embeddable
。 p>
@OneToOne
code> C C
关联被绑定到目标实体生命周期。
In my use-case, I would like to @Embedded
a class C
in an entity.
Another entity refers to C
with @OneToMany
association and therefore C
is annotated with @Entity
.
I am aware that this seems like bad design, yet I believe that it makes perfect sense in my case.
Is it possible to force Hibernate to embed an Entity? If I try it, Hibernate complains about a missing setter for the id property of C.
I think the problem comes from this:
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
Hibernate doesn't allow you to treat an Embeddable
as an Entity
or to embed an Entity
. According to Hibernate types:
- an
Embeddable
, doesn't have an identifier, since it's state is part of an owningEntity
. - an
Entity
cannot be embedded, because eachEntity
has a distinct life-cycle.
Since another class already has a @OneToMany
association to class C
, it's obvious you cannot turn it into an Embeddable
.
What you can do, is to use it as a @OneToOne
association in the entity where you wanted to embed the C
entity. You can make that target entity be the owning side of the association, so that the C
association is bound to the target entity life-cycle.
这篇关于Hibernate - 嵌入@Entity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!