日期:2014-05-20  浏览次数:20698 次

hibernate 关联问题
小弟看了马士兵的视频,但是在“一对一双向外键关联”和“一对一单向外键关联”中被搞糊涂了,感觉他们就是一回事情,看不出他们有什么区别,如下是我的代码:
这个是一对一双向外键关联:
Husband类:
package model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Husband {

private int id;
private String name;
private Wife wife;

@Id
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类:

package model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Wife {

private Husband husband; //这个去掉就是一对一单向外键关联
private int id;
private String name;

@OneToOne(mappedBy="wife") //这个去掉就是一对一单向外键关联
public Husband getHusband() { //这个去掉就是一对一单向外键关联
return husband; //这个去掉就是一对一单向外键关联
} //这个去掉就是一对一单向外键关联
@Id
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setHusband(Husband husband) { //这个去掉就是一对一单向外键关联
this.husband = husband; //这个去掉就是一对一单向外键关联
} //这个去掉就是一对一单向外键关联
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}

}


最终的出的结果都是:
  create table Husband (
  id integer not null,
  name varchar(255),
  WifeID integer,
  primary key (id)
  )

  create table Wife (
  id integer not null,
  name varchar(255),
  primary key (id)
  )

  alter table Husband 
  add index FKAEEA401B4BC12EC2 (WifeID), 
  add constraint FKAEEA401B4BC12EC2 
  foreign key (WifeID) 
  references Wife (id)

------解决方案--------------------
http://greenyouyou.blog.163.com/blog/static/138388147201131225239988/

看看这个文章,你的代码实在不想看了,或者帮你顶一下!
------解决方案--------------------
看书上的例子。。还不如网上有针对性的找些例子。。自己写。。。书上的东西有些写的有点死。。