天天看点

【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