Hibernate:1对1关系总结。
QQ和QQ空间是1对1关系:配置如下
一、主键关联,双方共同维护表关系,以主键关联
public class QQ { private Long id; private QQZone zone; }
public class QQZone { private Long id; private QQ qq; }
<hibernate-mapping package="com.bohe.domain"> <class name="QQ" table="qq"> <id name="id" column="ID"> <generator class="native" /> </id> <one-to-one name="zone" /> </class> </hibernate-mapping>
<hibernate-mapping package="com.bohe.domain"> <class name="QQZone" table="qqzone"> <id name="id" column="ID"> <generator class="native" /> </id> <one-to-one name="qq" /> </class> </hibernate-mapping>
二、用many-to-one模仿one-to-one,qq表为主表,qqzone为从表
public class QQ { private Long id; private QQZone zone; }
public class QQZone { private Long id; private QQ qq; }
<hibernate-mapping package="com.bohe.domain"> <class name="QQ" table="qq"> <id name="id" column="ID"> <generator class="native" /> </id> <one-to-one name="zone" /> </class> </hibernate-mapping>
<hibernate-mapping package="com.bohe.domain"> <class name="QQZone" table="qqzone"> <id name="id" column="ID"> <generator class="native" /> </id> <many-to-one name="qq" column="qq_id" unique="true"/> </class> </hibernate-mapping>