hibernate学习4-关联映射-多对一
关联映射分类
一对一,一对多(多对一),多对多
单向关联和双向关联
单向关联多对一
客户和订单
数据表:
customer(id,name,email)
order(id,name,orderNumber,customerId(外键))
类
Customer(Integerid,Stringname,Stringemail)
Order(Integerid,Stringname,StringorderNumber,Customercustomer)//不是customerId
映射文件customer.hbm.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="com.limf.bean.Customer"table="Customer">
<idname="id"column="id">
<generatorclass="native"></generator>
</id>
<propertyname="name"column="name"></property>
<propertyname="emai"column="email"></property>
</class>
</hibernate-mapping>
映射文件order.hbm.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="com.limf.bean.Order"table="Order">
<idname="id"column="id">
<generatorclass="native"></generator>
</id>
<propertyname="name"column="name"></property>
<propertyname="orderNumber"column="orderNumber"></property>
<many-to-onename="customer"class="com.limf.bean.Customer">
<columnname="customerId"></column>
</many-to-one>
</class>
</hibernate-mapping>
保存订单时需要先从数据库加载一个customer,调用order.setCustomer(Customerc)
当加载一个订单时,session.get(Order.class,orderId),得到order
再取得customer,order.getCustomer(),会报错
需要对Customer设置延迟加载false
修改customer.hbm.xml
<classname="com.limf.bean.Customer"table="Customer"lazy="false">
双向关联多对一
Customer类中增多一个属性Setorders=newHashSet()
映射文件customer.hbm.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="com.limf.bean.Customer"table="Customer">
<idname="id"column="id">
<generatorclass="native"></generator>
</id>
<propertyname="name"column="name"></property>
<propertyname="emai"column="email"></property>
<setname="orders"lazy="false"><!--不要延迟加载-->
<keycolumn="CustomerId"/><!--集合外键-->
<one-to-manyclass="com.limf.bean.Order"/>
</set>
</class>
</hibernate-mapping>