How to store some of the entity's values in another table using hibernate?
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 开发者_如何学运维:)
- map
Addressas an entity and add a primary key (an auto-generated id) - map the relation between
PersonandAddressasone-to-one(@OneToOneon each field)
With Hibernate 3.5 it is possible to define foreign generators (aka. JPA mapping), details are here.
It is pretty straight forward Person should implement Serializable then @Id annotation is added to person.
@Entity
@AccessType(value = "field")
@Table(name = "addresses")
public class Address
{
@Id
@OneToOne
@JoinColumn(name = "person_id")
private Person person;
// ...
}
There is an alternative but I really like the first one:
@Entity
@AccessType(value = "field")
@Table(name = "addresses")
public class Address
{
@Id
private int personId;
@MapsId
@OneToOne
@JoinColumn(name = "person_id")
private Person person;
// ...
}
加载中,请稍侯......
精彩评论