1.无连接表的单向一对一
- 单向一对一与单向多对一很相似
- 需要在一的一方添加注解@OneToOne @JoinColumn(name="",unique=true) 因为是一对一,所有要unique=true
- 主要代码及例子
- 在一的一方添加注解@OneToOne(cascade={CascadeType.ALL}) @JoinColumn(name="",unique=true)
<span style="font-family:Microsoft YaHei;">//表一学生表(假如:一个学生只能有一个地址)
@Entity
@Table(name = "T_JC_test1")
@Where(clause="recordStatus='"+GlobalConstant.FLAG_Y+"'")
public class Test1 extends BusinessEntity{
private static final long serialVersionUID = 2535128385272676564L;
private String name;
private Test2 address;
@OneToOne(cascade={CascadeType.ALL})
@JoinColumn(name="test1ID",unique=true)
public Test2 getAddress() {
return address;
}
public void setAddress(Test2 address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//表二,地址表
@Entity
@Table(name = "T_JC_test2")
@Where(clause="recordStatus='"+GlobalConstant.FLAG_Y+"'")
public class Test2 extends BusinessEntity{
private static final long serialVersionUID = -7653945367481001205L;
private String addressDetatil;
public String getAddressDetatil() {
return addressDetatil;
}
public void setAddressDetatil(String addressDetatil) {
this.addressDetatil = addressDetatil;
}
}
</span>
2.有链接表的单向一对一- 有链接表的单向一对一只需在一的一方添加注解@OneToOne(cascade={CascadeType.ALL}) @JoinTable(name="T_JC_test1_test2",joinColumns=@JoinColumn(name="test1ID",unique=true),inverseJoinColumns=@JoinColumn(name="test2ID",unique=true))
- 例子如下
<span style="font-family:Microsoft YaHei;">//表一,学生表
@Entity
@Table(name = "T_JC_test1")
@Where(clause="recordStatus='"+GlobalConstant.FLAG_Y+"'")
public class Test1 extends BusinessEntity{
private static final long serialVersionUID = 2535128385272676564L;
private String name;
private Test2 address;<span style="white-space:pre"> </span>//引用表二
@OneToOne(cascade={CascadeType.ALL})
@JoinTable(name="T_JC_test1_test2",joinColumns=@JoinColumn(name="test1ID",unique=true),inverseJoinColumns=@JoinColumn(name="test2ID",unique=true))
public Test2 getAddress() {
return address;
}
public void setAddress(Test2 address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//表二,地址表
@Entity
@Table(name = "T_JC_test2")
@Where(clause="recordStatus='"+GlobalConstant.FLAG_Y+"'")
public class Test2 extends BusinessEntity{
private static final long serialVersionUID = -7653945367481001205L;
private String addressDetatil;
public String getAddressDetatil() {
return addressDetatil;
}
public void setAddressDetatil(String addressDetatil) {
this.addressDetatil = addressDetatil;
}
}</span>