【hibernate框架】关系映射之一对一单项外键关联(Annotation实现)

一对一单向外键关联(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"


转载请注明出处:http://blog.csdn.net/acmman

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光仔December

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值