hibernate学习4-关联映射-多对一
关联映射分类
一对一,一对多(多对一),多对多
单向关联和双向关联
单向关联 多对一
客户和订单
数据表:
customer(id,name,email)
order(id,name,orderNumber,customerId(外键))
类
Customer(Integer id,String name,String email)
Order(Integer id,String name,String orderNumber,Customer customer)//不是customerId
映射文件customer.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.limf.bean.Customer" table="Customer">
<id name="id" column="id">
<generator column="name"></property>
<property name="emai" column="email"></property>
</class>
</hibernate-mapping>
映射文件order.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.limf.bean.Order" table="Order">
<id name="id" column="id">
<generator column="name"></property>
<property name="orderNumber" column="orderNumber"></property>
<many-to-one name="customer" table="Customer" lazy="false">
双向关联 多对一
Customer类中增多一个属性Set orders = new HashSet()
映射文件customer.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.limf.bean.Customer" table="Customer">
<id name="id" column="id">
<generator column="name"></property>
<property name="emai" column="email"></property>
<set name="orders" lazy="false"> <!--不要延迟加载-->
<key column="CustomerId"/> <!--集合外键-->
<one-to-many class="com.limf.bean.Order"/>
</set>
</class>
</hibernate-mapping>