假定Person類和PersonDetail類爲一對一關聯關係,相應的,PERSONS表和PERSON_DETAILS表爲一對一參照關係。PERSON_DETAILS表的ID字段既是主鍵,又做爲外鍵參照PERSONS表的ID主鍵,所以,PERSON_DETAILS表的ID主鍵實際上來自於PERSONS表的ID主鍵。PERSON_DETAILS表的ID主鍵稱爲派生主鍵。java
Person類的定義以下:markdown
@Entity @Table(name="PERSONS") public static class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="ID") private Long id; @Column(name="NAME") private String name; …… }
在如下PersonDetail類中,person屬性使用了@MapsId註解,代表PersonDetail類的id屬性的值來自於person屬性所引用的Person對象的id屬性。ide
@Entity @Table(name="PERSON_DETAILS") public static class PersonDetail { @Id @Column(name="ID") private Long id; @OneToOne @JoinColumn(name=" ID") @MapsId private Person person; @Column(name="NICK_NAME") private String nickName; …… }
PERSON表和PERSON_DETAILS表的DDL定義語句以下:atom
create table PERSONS (ID bigint not null auto_increment, NAME varchar(15),primary key (ID)); create table PERSON_DETAILS (ID bigint not null, NICK_NAME varchar(15),primary key (ID)); alter table PERSON_DETAILS add index IDX_PERSON (ID), add constraint FK_PERSON foreign key(ID) references PERSONS(ID);
如下代碼先建立一個Person對象和PersonDetail對象,再對它們持久化:spa
Person person = new Person("Tom"); PersonDetail personDetail = new PersonDetail(); personDetail.setNickName( "SunShine" ); personDetail.setPerson( person ); …… entityManager.persist( person ); entityManager.persist( personDetail ); System.out.println("Person ID:"+person.getId()); System.out.println("PersonDetail ID:"+personDetail.getId());
以上Person對象的id標識符經過identity標識符生成器產生,而PersonDetail對象的id標識符來自於Person對象的id標識符。以上代碼的打印結果以下:code
Person ID:8 PersonDetail ID:8