问题描述
在我的用例中,我想在实体中@Embedded
一个类C
.
In my use-case, I would like to @Embedded
a class C
in an entity.
另一个实体引用具有@OneToMany
关联的C
,因此C
用@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.
是否可以强制Hibernate嵌入实体?如果尝试,Hibernate会抱怨C的id属性缺少setter.
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.
我认为问题出在此:
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
推荐答案
Hibernate不允许您将Embeddable
视为Entity
或嵌入Entity
.根据休眠类型:
Hibernate doesn't allow you to treat an Embeddable
as an Entity
or to embed an Entity
. According to Hibernate types:
- 一个
Embeddable
,没有标识符,因为它的状态是拥有的Entity
的一部分. -
Entity
不能被嵌入,因为每个Entity
都有不同的生命周期.
- 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.
由于另一个类已经具有与C
类的@OneToMany
关联,因此很明显,您无法将其转换为Embeddable
.
Since another class already has a @OneToMany
association to class C
, it's obvious you cannot turn it into an Embeddable
.
更多,双向@OneToMany
关联的性能将优于可嵌入的集合.
您可以做的是,将其用作要嵌入C
实体的实体中的@OneToOne
关联.您可以使目标实体成为关联的拥有方,以便将C
关联绑定到目标实体的生命周期.
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嵌入实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!