hibernate关联弱问
弱问?
hibernate中提到的一对一单向外键关联和一对一双向外键关联,这个单向和双向怎么理解啊?最好给个例子。谢谢
------解决方案--------------------设置双向外键关联与单向外键关联的区别是,在每个类都有对方类的引用.
同时,用annotation标签注解,只以那个来做关联,这样就不会生出多个外键关联
看例子,首先建立两个类分别如下
@Entity
public class Husband {
private int id;
private String name;
private Wife wife;
@OneToOne
public Wife getWife() {
return wife;
}
.....
然后建立另一个类
@Entity
public class Wife {
private int id;
private String name;
private Husband husband;
@OneToOne
public Husband getHusband() {
return husband;
}
public void setHusband(Husband husband) {
this.husband = husband;
}
......
这两个类都有对方的引用.就构成了多对多的条件.运行自动建表程序(同一对一单向外键关联),看结果
11:46:35,718 DEBUG SchemaExport:377 -
create table Husband (
id number(10,0) not null,
name varchar2(255),
wife_id number(10,0),
primary key (id)
)
11:46:35,750 DEBUG SchemaExport:377 -
create table Wife (
id number(10,0) not null,
name varchar2(255),
husband_id number(10,0),
primary key (id)
)
11:46:35,765 DEBUG SchemaExport:377 -
alter table Husband
add constraint FKAEEA401B74A158F3
foreign key (wife_id)
references Wife
11:46:35,781 DEBUG SchemaExport:377 -
alter table Wife
add constraint FK292331AE37DC61
foreign key (husband_id)
references Husband
11:46:35,796 DEBUG SchemaExport:377 -
create sequence hibernate_sequence
11:46:35,812 INFO SchemaExport:268 - schema export complete
可以看到建立了两张表,同时两张表都建立了外键的关联.但是这样造成冗余,关键是更新表记录的时候麻烦,因为你还要互相考虑到关联性,所以一般是一个表建立了外键就行.那么怎么实现?
看例子
修改其中某个类的get方法,以wife类为例,修改如下
public class Wife {
private int id;
private String name;
private Husband husband;
@OneToOne(mappedBy="wife")
public Husband getHusband() {
return husband;
}
...
这段话的具体理解是,首先Wife这个类是与Husband类做一对一关联的,同时是以Husband类里面的getWife()这个属性来做maping的,做映射的.这个时候,就只在husband表生成外键.(简单理解,两个类的外键关联,以一个类为准,只在husband表生成外键,wife表不需要生成外键)
看结果
11:58:01,343 DEBUG SchemaExport:377 -
create table Husband (
id number(10,0) not null,
name varchar2(255),
wife_id number(10,0),
primary key (id)
)
11:58:01,375 DEBUG SchemaExport:377 -
create table Wife (
id number(10,0) not null,
name varchar2(255),
primary key (id)
)
11:58:01,453 DEBUG SchemaExport:377 -
alter table Husband
add constraint FKAEEA401B74A158F3
foreign key (wife_id)
references Wife
11:58:01,468 DEBUG SchemaExport:377 -
create sequence hibernate_sequence
11:58:01,468 INFO SchemaExport:268 - schema export complete
------解决方案--------------------简单点说,比如人和身份证,这是一个一对一关系吧,所谓单向关联就是你只在某一端配置了<one-to-one>标签,这里我们假设你在人这端配置了这个标签,那么当你查询一个人的时候,就能查到身份证的信息,但是你要是想通过查身份证去查人的信息的话就不行,因为你这是一个单向关联,你没有在身份证中配置<one-to-one>标签,所谓双向关联就是你在身份证中也配置<one-to-one>标签.