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 class="native"></generator>
</id>

<property name="name" 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 class="native"></generator>
</id>

<property name="name" column="name"></property>
<property name="orderNumber" column="orderNumber"></property>

<many-to-one name="customer" class="com.limf.bean.Customer">
<column name="customerId"></column>
</many-to-one>

</class>
</hibernate-mapping>


保存订单时需要先从数据库加载一个customer,调用order.setCustomer(Customer c)

当加载一个订单时,session.get(Order.class,orderId),得到order
再取得customer,order.getCustomer(),会报错
需要对Customer设置延迟加载false
修改customer.hbm.xml
<class name="com.limf.bean.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 class="native"></generator>
</id>

<property name="name" 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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值