是否可以强制Hibernate嵌入实体? [英] Is it possible to force Hibernate to embed an Entity?

查看:78
本文介绍了是否可以强制Hibernate嵌入实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的用例中,我想在实体中@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 owning Entity.
  • an Entity cannot be embedded, because each Entity 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嵌入实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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