一对一单向外键关联(Annotation做法):

例子,假设一夫配一妻(Husband与Wife)。两个实体类的例子:

Husband.java:

package cn.edu.hpu.one2one;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;


@Entity
public class Husband {
private int id;
private String name;
private Wife wife;


@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

@OneToOne //在数据库中会生成Wife_id字段
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}




Wife.java:


package cn.edu.hpu.one2one;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;


@Entity
public class Wife {
private int id;
private String name;


@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}




剖析:在实体类中,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 (

id integer not null auto_increment,

name varchar(255),

primary key (id)

)


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来指定你想要的外键的字段名。


示例:


@OneToOne
@JoinColumn(name="wifeid")
public Wife getWife() {
return wife;
}

数据库中husband的外键字段名就变为"wifeid"