hibernate之一对一
一对一实际上是特殊的多对一,只是将那个多变成了唯一,我这里写的一对一配置,采用的是相同字段的主键的一对一,一个表的主键可以引用另一表的主键作为自己的主键
表一:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping package="com.newtouch.entity" auto-import = "true"> <class name="Account" table="account" > <id name="userid" > <generator class="foreign"> <param name="property">signon</param> </generator> </id> <one-to-one name="signon" class="Signon" constrained="true"></one-to-one> </class> </hibernate-mapping>
表二:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.newtouch.entity" > <class name="Signon" table="signon" > <id name="username"> <generator class="assigned"/> </id> <one-to-one name="account" class="Account"></one-to-one> </class> </hibernate-mapping>
明显account引用了signon的主键,所以,在插入数据时把signon 给set进account即可