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.

转载于:https://www.cnblogs.com/honbaa/p/3343771.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值