13.1:1映射
husband与wife
类图:(对象之间的对应)
一个husband对应一个wife,故wife的多重性为1;
一个wife对应一个husband,故husband多重性为1;
现在确定导航性为:Husband可以找到Wife。则在husband类中,包含一个Wife对象即可。
POJO为:
Husband.java:
@Entity public class Husband { private int id; private String name; private Wife wife; @Id @GeneratedValue public int getId() { return id; } public String getName() { return name; } @OneToOne @JoinColumn(name="wifeID")//实际上就是制定了外键列名,而不是用默认的。 public Wife getWife() { return wife; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setWife(Wife wife) { this.wife = wife; } }
Wife.java:
@Entity public class Wife { private int id; private String name; @Id public int getId() { return id; } public String getName() { return name; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } }
在hibernate.cfg.xml中加入这2个实体bean.
<mapping class="zhx1529.model.Wife" /> <mapping class="zhx1529.model.Husband" />
在测试程序中,使用SchemaExport即可以自动建表。查看ddl语句:
create table Wife ( id integer not null, name varchar(255), primary key (id) ) create table Husband ( id integer not null auto_increment, name varchar(255), wifeID integer, primary key (id) ) alter table Husband add index FKAEEA401B7DD06CDB (wifeID), add constraint FKAEEA401B7DD06CDB foreign key (wifeID) references Wife (id)
使用mysql workbench执行反向工程,查看er model:
可以看到:
表的1:1关系的实体bean设计为:每个bean同样包含所有字段,再将外键用一个被导航对象代替。