Hibernate关系处理之一对一
在实际的处理问题中, 一对一的关系我们可以将其看做是一个一对多的特例. 将多放限制一下, 只能有一个实例即可.
现实生活中, 一个ip地址是可以指派给不同的电脑, 但是同时只能有一个电脑在使用此地址.示例如下:
public class Comp implements java.io.Serializable {private Integer comid;private Ipaddr ipaddr; public Comp() {}public Integer getComid() {return this.comid;}public void setComid(Integer comid) {this.comid = comid;}public Ipaddr getIpaddr() {return this.ipaddr;}public void setIpaddr(Ipaddr ipaddr) {this.ipaddr = ipaddr;}}?
public class Ipaddr implements java.io.Serializable {private Integer id;private String ipaddr;private Comp comp ;public Ipaddr() {}public Integer getId() {return this.id;}public void setId(Integer id) {this.id = id;}public String getIpaddr() {return this.ipaddr;}public void setIpaddr(String ipaddr) {this.ipaddr = ipaddr;}public Comp getComp() {return comp;}public void setComp(Comp comp) {this.comp = comp;}}?
我们可以看出, 一台电脑配置一个ip地址, 或者说一个ip地址同时只能指派给一台电脑.
?
xml配置文件如下.
?
<class name="Comp" table="comp" catalog="hibernate"> <id name="comid" type="java.lang.Integer"> <column name="comId" /> <generator /> </id> <many-to-one name="ipaddr" cascade="save-update" fetch="select" > <column name="ipaddr" not-null="true" unique="true" /> </many-to-one></class>
?上面可以看出, 电脑和ip地址是可以单独存在的两个实体. 一个ip地址可以指派给多台电脑. 但是多方Comp却在column属性中加入了unique和notnull约束.
?? <many-to-one name="ipaddr" cascade="save-update" fetch="select" >
????????? <column name="ipaddr" not-null="true" unique="true" />
?? </many-to-one>
?
我们再看看一方的配置
<class name="Ipaddr" table="ipaddr" catalog="hibernate" > <id name="ipaddrId" type="java.lang.Integer"> <column name="ipaddr_id" length="10" /> <generator /> </id> <one-to-one name="comp" cascade="all" property-ref="ipaddr"></one-to-one></class>
?在这个一对一的例子中需要确定一点, 谁是主, 谁是子.
主方配置<one-to-one name="comp" cascade="all" property-ref="ipaddr" ></one-to-one>
子方配置<many-to-one name="ipaddr" cascade="save-update" fetch="select">
? <column name="ipaddr" not-null="true" unique="true" />
</many-to-one>
?
还有一种一对一的关系. 子方的外键还做子方的主键. 如一个设备激活的时候需要一个激活码,而这个激活码只能供一个设备使用一次,该设备被激活码激活绑定后就不能再被其他的激活码激活绑定.
?
public class Equipment implements java.io.Serializable {? private Integer eacId; private EACard EACard;public EACard getEACard() {return this.EACard;}public void setEACard(EACard EACard) {this.EACard = EACard;}}?
?
public class EACard implements java.io.Serializable { private Equipment equipment;? private Integer eacId;public Equipment getEquipment() {return this.equipment;}public void setEquipment(Equipment equipment) {this.equipment = equipment;}}?
从上面的java类中可以看出, 每个eac都有一个eacId标识. 并且每个设备激活码都有一个设备属性. 所以设备激活码是主方. 设备时子方.
?
<class name="EACard" table = "eacard" catalog="hibernate" > <id name="eacard" type = "java.lang.Integer"> <column name="eacard" length=15/> <generator lazy="proxy"></one-to-one></class>
?
<class name="Equipment" table="equipment" catalog="hibernate"> <id name="eaCard" type="integer"> <column name="eacard" /> <generator constraint="true" lazy="proxy" ></one-to-one></class>
?
在有外键的一方增加constraint="true"属性.