一 表结构:
CREATE TABLE `address` (
`aid` int(11) NOT NULL auto_increment,
`address` varchar(255) NOT NULL default '',
PRIMARY KEY (`aid`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
CREATE TABLE `user` (
`userid` int(11) NOT NULL auto_increment,
`username` varchar(255) NOT NULL default '',
`age` int(2) default NULL,
`addressID` int(11) default NULL, --外键
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
二 POJO与映射文件
public class User {
private Integer userid;
private String username;
private Integer age;
private Address address;
//getters setters method...
}
public class Address {
private Integer aid;
private String address;
private User user;
//getters setters method...
}
User.hbm.xml
<class name="com.pojo.User" table="user" dynamic-insert="true"
dynamic-update="true">
<id name="userid" type="integer">
<column name="userid" sql-type="int" length="11"></column>
<generator class="native"></generator>
</id>
<property name="username" type="string">
<column name="username" sql-type="varchar" length="255"
not-null="true">
</column>
</property>
<property name="age" type="integer">
<column name="age" sql-type="int" length="2"></column>
</property>
<many-to-one name="address" class="com.pojo.Address"
cascade="all" column="addressID" unique="true">
</many-to-one>
</class>
</hibernate-mapping>
Address.hbm.xml
<hibernate-mapping>
<class name="com.pojo.Address" table="address" dynamic-insert="true" dynamic-update="true">
<id name="aid" type="integer">
<column name="aid" sql-type="int" length="11"></column>
<generator class="native">
</generator>
</id>
<property name="address" type="string">
<column name="address" sql-type="varchar" length="255"></column>
</property>
<one-to-one name="user" class="com.pojo.User"
constrained="true" cascade="all" property-ref="address">
</one-to-one>
</class>
</hibernate-mapping>