Hibernate 中的组合如何工作?
我正在尝试在休眠中使用带有注释的组合。
我有:
@Entity
@Table(name = "Foo")
public class Foo {
private Bar bar;
public void setBar(Bar bar){...}
public Bar getBar() {...)
}
public class Bar {
private double x;
public void setX(double x) {...}
public double getX() {...}
}
当试图拯救 Foo 时,我得到了
无法确定实体的类型 org.bla.Bar 位于表 Foo 的列: [org.hibernate.mapping.Column(bar)]
我尝试在 Bar 上添加 @Entity 注释,但这让我感到困惑:
没有为实体指定标识符 org.bla.Bar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
参考文档的本节描述了该机制:
5.1.5。嵌入式对象(又名组件)
显然,hibernate 使用 JPA 注释来实现此目的,因此解决方案 Ralph 引用的内容是正确的
简而言之:
如果将类
Address
标记为@Embeddable
并添加类型 < 的属性code>Address 到类User
,将属性标记为@Embedded
,然后生成的数据库表User
将指定所有字段通过地址
。请参阅拉尔夫的答案以获取代码。
The mechanism is described in this section of the reference docs:
5.1.5. Embedded objects (aka components)
Apparently hibernate uses JPA annotations for this purpose, so the solution referred to by Ralph is correct
In a nutshell:
if you mark a class
Address
as@Embeddable
and add a property of typeAddress
to classUser
, marking the property as@Embedded
, then the resulting database tableUser
will have all fields specified byAddress
.See Ralph's answer for the code.
您需要指定
Foo
和Bar
之间的关系(使用 @ManyToOne 或 @OneToOne 之类的东西)。或者,如果
Bar
不是实体,则用 @Embeddable 标记它,并将 @Embedded 添加到Foo
中的变量声明中。请参阅:https://www.baeldung.com/jpa-embedded-embeddable - - 该示例解释了@Embeddable和@Embedded Composite方式,其中
Foo
和Bar
(Company
和ContactPerson
在示例)映射在同一个表中。You need to specifiy the relationship between
Foo
andBar
(with something like @ManyToOne or @OneToOne).Alternatively, if
Bar
is not an Entity, then mark it with @Embeddable, and add @Embedded to the variable declaration inFoo
.See: https://www.baeldung.com/jpa-embedded-embeddable -- The example expains the @Embeddable and @Embedded Composite way, where
Foo
andBar
(Company
andContactPerson
in the example) are mapped in the same Table.每个简单实体必须标记为实体(使用
@Entity
)并具有一个标识符(主要是长整型)作为主键。每个非原始关联/组合必须使用相应的关联注释(@OneToOne
、@OneToMany
、@ManyToMany
)进行声明。我建议您仔细阅读 Hibernate 入门指南 。请尝试以下操作以使您的代码示例正常工作Each simple entity must be marked as an entity (with
@Entity
) and have an identifier (mostly a Long) as a primary key. Each non-primitive association/composition must be declared with the corresponding association annotation (@OneToOne
,@OneToMany
,@ManyToMany
). I suggest you read through the Hibernate Getting Started Guide. Try the following to make your code example work