开发者

How to store some of the entity's values in another table using hibernate?

开发者 https://www.devze.com 2022-12-26 01:03 出处:网络
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.

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 开发者_如何学运维:)


  1. map Address as an entity and add a primary key (an auto-generated id)
  2. map the relation between Person and Address as one-to-one (@OneToOne on 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;
   // ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消