13.1:1映射

husband与wife

类图:(对象之间的对应)

一个husband对应一个wife,故wife的多重性为1;

一个wife对应一个husband,故husband多重性为1;

类图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:

husband and wife

可以看到:

表的1:1关系的实体bean设计为:每个bean同样包含所有字段,再将外键用一个被导航对象代替。

hibernate将面向对象实体bean出发,可以自动生成相应的表
对象关系和表关系的映射是可逆的同样可以根据数据库的表关系,设计出符合面向对象标准的实体bean.
posted @ 2013-09-27 23:27  FishBird  阅读(167)  评论(0编辑  收藏  举报