OneToOne annotation 双向关联
程序员文章站
2022-03-02 15:22:13
...
package com.hibernate.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
@Entity
public class Husband implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2476364405175138004L;
private int id;
private String name;
private Wife wife;
@Id
@GeneratedValue
public int getId() {
return id;
}
public String getName() {
return name;
}
@OneToOne
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;
}
}
package com.hibernate.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
@Entity
public class Wife implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5270130768836331730L;
private int id;
private String name;
private Husband husband;
@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;
}
@OneToOne(mappedBy="wife")
public Husband getHusband() {
return husband;
}
public void setHusband(Husband husband) {
this.husband = husband;
}
}
注意 :Wife类的getHusband()上用了mappedBy"wife"
这个意思是说,我这里的OneToOne就不用管了,只用Husband里的getWife()上的OneToOne关系
生成的表为Husband参考Wife,有了wifeid,才能有Husband
Husband为这个关系的拥有者
如果Wife类的getHusband()只有@OneToOne,没有mappedBy,那么生成的两张表都会有对方的外键,造成外键冗余。
上一篇: 单向关联和双向关联
下一篇: 基于g2的viserjs