More Related Content
Similar to 10 hibernate 多对多关系映射
Similar to 10 hibernate 多对多关系映射 (13)
10 hibernate 多对多关系映射
- 3. 多对多关系映射
关系: User( 用户 ) -- Roles( 权限 )
表结构: ( 会使用关联表 )
Users( 表 ) Roles( 表 )
userId userName roleId roleName
----------------------------------- -------------------------------
D001 张三 1 添加
D002 李四 2 删除
D003 王五 3 修改
…… ……
Users_Roles( 表 )
userId roleId
-----------------------------------
D001 1
D001 3
D003 1
……
www.sodi.com.cn
- 4. 多对多关系映射
多对多关系的对象模型 ( 双向 )
Users( 用户 ) -- Roles( 权限 )
Users( 类 ) Roles( 类 )
userId: String roleId: int
userName:String roleName: String
roles: Set( 集合 ) users: Set ( 集合 )
www.sodi.com.cn
- 5. 多对多关系 -- 映射文件
Roles.hbm.xml:
<hibernate-mapping package="com.sodi.entity">
<class name="Roles" table="tab_roles">
<id name="roleId" column="roleid">
<generator class="assigned"/>
</id>
<property name="roleName" column="rolename"/>
<set name="users" table="tab_user_roles">
<key column="roleid"/>
<many-to-many class="Users" column="userid" />
</set>
</class>
</hibernate-mapping>
www.sodi.com.cn
- 6. 多对多关系 -- 映射文件
Users.hbm.xml:
<hibernate-mapping package="com.sodi.entity">
<class name="Users" table="tab_user">
<id name="userId" column="userid">
<generator class="assigned"/>
</id>
<property name="userName" column="username"/>
<!-- 多对多关系中由另一方维持关联关系,由权限方来维持 -->
<set name="roles" table="tab_user_roles" inverse="true">
<key column="userid"/>
<many-to-many class="Roles" column="roleid" />
</set>
</class>
</hibernate-mapping>
www.sodi.com.cn
- 7. 多对多关系 -- 映射文件
注意点:
table 属性值必须和单向关联中的 table 属性值
一致
<key> 中 column 属性值要与单向关联中的
<many-to-many> 标签中的 column 属性值
一致
在 <many-to-many> 中的 column 属性值要
与单向关联中 <key> 标签的 column 属性值一
致
www.sodi.com.cn
- 8. 操作演示
操作演示
www.sodi.com.cn