如何使用休眠将一些实体的值存储在另一个表中?
有没有一种简单的方法可以使用 hibernate 将某些字段保留在另一个类和表中。
例如,我有一个包含 name
、surname
、email
、address1
的 Person
类>、地址2
、城市
、国家
字段。我希望我的课程是:
public class Person
{
private String name;
private String surname;
private String email;
private Address address;
// ..
}
public class Address
{
private Person person; // to whom this belongs
private String address1;
private String address2;
private String city;
private String country;
// ..
}
我想将地址存储在另一个表中。实现这一目标的最佳方法是什么?
编辑:我正在使用注释。它不一定是我所描述的方式,我正在寻找最佳实践。
编辑 2: 地址的 ID 是什么?
附言。如果有一种方法可以使 Address 不可变(用作值对象)那就更好了,或者可能不是,因为我从错误的角度思考一切:)
is there a simple way to persist some of the fields in another class and table using hibernate.
For example, I have a Person
class with name
, surname
, email
, address1
, address2
, city
, country
fields. I want my classes to be:
public class Person
{
private String name;
private String surname;
private String email;
private Address address;
// ..
}
public class Address
{
private Person person; // to whom this belongs
private String address1;
private String address2;
private String city;
private String country;
// ..
}
and I want to store Address in another table. What is the best way to achieve this?
Edit: I am using annotations. It does not have to be the way I described, I am looking for best practices.
Edit 2: What will be the Id of Address?
PS. If there is a way to make Address immutable (to use as a value object) that is even better, or maybe not because I thought everything from wrong perspective :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Address
映射为实体并添加主键(自动生成的 ID)Person
和Address
之间的关系映射为one -to-one
(每个字段上的@OneToOne
)Address
as an entity and add a primary key (an auto-generated id)Person
andAddress
asone-to-one
(@OneToOne
on each field)使用 Hibernate 3.5 可以定义外部生成器(又名 JPA 映射),详细信息为 此处。
这是非常简单的
Person
应该实现Serialized
然后将@Id
注释添加到person
中。还有一个替代方案,但我真的很喜欢第一个:
With Hibernate 3.5 it is possible to define foreign generators (aka. JPA mapping), details are here.
It is pretty straight forward
Person
should implementSerializable
then@Id
annotation is added toperson
.There is an alternative but I really like the first one: