Hibernate学习笔记3--映射关联关系

来源:互联网 发布:windows 高精度sleep 编辑:程序博客网 时间:2024/04/26 03:12

1.多对一(以customer和order为例子)


属性:

customer:customerId,customerNameorder:orderId,orderName,Customer customer

order.hbm.xml中的部分配置:

<many-to-one name="customer" class="customer的全类名" column="customer_id"/>

说明:
1.column=”customer_id”是order表中关联customer的外键名。
2.在查询order的时候可能会出现懒加载,因为只有用到customer的时候才会发送查询语句。
3.插入的时候先插入多的一端(order)这样才不会出现update语句。

2.一对多(以customer和order为例子)


属性:

customer:customerId,customerName,Set<Order> orders=new  HashSet<>()order:orderId,orderName,Customer customer

order.hbm.xml的部分配置:

<many-to-one name="customer" class="customer的全类名" column="customer_id">

customer.hbm.xml中的部分配置:

<set name="orders" table="order" reverse="true">    <key column="customer_id(order表中对应customer的外键)"/>    <one-to-many class="order的全类名"/></set>

插入的时候:先插入1(customer)的1端,再插入多(order)的一端,并在set集合中设置reverse=”true”(通过reverse的属性来决定谁来维护关系(不能两个都来维护,reverse=”false”的一方来维护,默认false)),这样有不会出现多余的update语句。

3.基于外键映射的一对一关系


属性

Manager.java:mgrId,mgrName,Deptment deptDepartMent.java:deptid,deptName,Manager mgr

department中有外键mgr_id
Department中hbm的配置(有外键的一端用many-to-one)

<many-to-one name="mgr" class="manager的全类名" column="mgr_id" unique="true"/>

manager.hbm.xml的部分配置(没外键的用one-to-one)

<one-to-one name="dept" class="department的全类名" property-ref="mgr">

说明:使用property-ref=”mgr”来说明对方映射文件中外键列对应的属性名。

4.基于主键映射的一对一关系


。。。。。。

5.多对多关联关系的映射(以category(种类)和item(商品)为例


多对多的关联关系在数据库的关联方式:有一个中间表,里面有两个字段是两个表的外键。
先以单向多对多为例子:

Category:id,name ,Set<Item> items=new HashSet<>()Item:id,name

Intem.hbm.xml的配置正常就行
Category.hbm.xml中对items属性的配置

<set  name=”items” table=”category_item”>    <key>        <column name=”c_id”>    </key>    <many-to-many class=”item” column=”i_id”><many-to-many></set>

说明:set中的table是中间表
Key中的column=”c_id”是category表在中间表中的外键
Many-to-many中的column=”i_id”是item表在中间表中的外键
双向多对多同理,但item需加上Set category=new HashSet<>(),同时也需要在item.hbm.xml中配置set,但中间表的表名和外键名都要和category中的配置相对应。同时要在其中的一个set中指定inverse=”true”

0 0
原创粉丝点击