天天看點

【hibernate架構】關系映射之一對一單項外鍵關聯(Annotation實作)

一對一單向外鍵關聯(annotation做法):

例子,假設一夫配一妻(husband與wife)。兩個實體類的例子:

husband.java:

wife.java:

剖析:在實體類中,husband有wife的引用,而wife裡面沒有,這就構成了一對一單向關聯。如何建表呢?

有關于建表,可以這樣思考:

肯定是兩張表,一張表示wife,一張表是husband。

husband: id(int)<pk,fk>、name(char)、wife_id<fk>(pk_reference_1->wife(主鍵關聯))

wife: id(int)<pk>、name(char) 

也可以設計關聯表,即husband和wife的對應表(這裡就不建立了)

husband_wife:hus_id int <fk1>、wif_id int <fk2>

在測試例子中用schemaexport來建表,成功。

@test

public void testschemaexport(){

new schemaexport(new annotationconfiguration().configure()).create(true, true);

}

列印出的建表語句為:

 alter table husband 

        drop 

        foreign key fkaeea401b45202e0a

    drop table if exists husband

    drop table if exists wife

    create table husband (

        id integer not null auto_increment,

        name varchar(255),

        wife_id integer,

        primary key (id)

    )

    create table wife (

    alter table husband 

        add index fkaeea401b45202e0a (wife_id), 

        add constraint fkaeea401b45202e0a 

        foreign key (wife_id) 

        references wife (id)

schema export complete

@onetoone有哪些屬性可以使用呢?

有cascade、fetch、mappedby、optional、targetentity。

不想使用hibernate預設的外鍵的名字“wife_id”,就用annotation中的@joincolumn來指定你想要的外鍵的字段名。

示例:

資料庫中husband的外鍵字段名就變為"wifeid"

轉載請注明出處:http://blog.csdn.net/acmman