Hibernate的学习中遇到几种映射关系:多对一,一对多和多对多的三种关系配置的流程总结:
1.写注释:
格式为:?属性,表达的是本对象与?的?关系。例:<!-- department属性,本类User与Department的多对一 -->
2.拷模板
多对一:
<many-to-one name=“” class=“” column=“”/>
一对多(Set):
<set name="">
<key column=""></key>
<one-to-many class=""/>
</set>
<set name="" table="">
<key column=""></key>
<many-to-many class="" column=""/>
</set>
3. 填空
4 完成
这里举例说明:
<!-- department属性,本类User与Department的多对一 -->
<many-to-one name="department" class ="Department" column="departmentId"></many-to-one>
<!-- users属性,本类Department与User的一对多的 -->
<set name="users" >
<key column="departmentId"></key>
<one-to-many class="User"/>
</set>
这里的column = “departmentId” ,我的理解:不管是多对一和一对多,只要把少的的那方当成外键,如User和Department的关系中department属于少的,就把department加上id当成外键。
多对多的例子:
<!-- users属性。本类Role与User的多对多 -->
<set name="users" table="user_role">
<key column="roleId"></key>
<many-to-many class="User" column="userId"></many-to-many>
</set>
这里的key column="roleId" 就是本类Role后加上Id,然后拷贝到<!-- roles的属性,本类User与Role的多对多 -->中的
<many-to-many class="Role" column="roleId"></many-to-many>中的column属性值
table属性值可任意定义,但是要与后面<!-- roles的属性,本类User与Role的多对多 -->中table值一致。
<!-- roles的属性,本类User与Role的多对多 -->
<set name="roles" table="user_role">
<key column="userId"></key>
<many-to-many class="Role" column="roleId"></many-to-many>
</set>
这里的key column="userId" 就是本类User后加上Id,然后拷贝到<!-- users属性。本类Role与User的多对多 -->中的
<many-to-many class="User" column="userId"></many-to-many>中的column属性值