Hibernate - 嵌入@Entity? [英] Hibernate - embedded @Entity?

查看:161
本文介绍了Hibernate - 嵌入@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 owning Entity.
  • an Entity cannot be embedded, because each Entity 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屋!

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