首页 > Web开发 > 详细

hibernate映射文件,实现一对多、多对一、多对多的映射关系

时间:2017-03-20 18:51:27      阅读:321      评论:0      收藏:0      [点我收藏+]

一、一对多和一对多的映射关系

1、在ChangeInformation实体类:

private Secondary secondary;//信息变更所属学生

加上get、set方法

2、在ChangeInformation.hbm.xml中

通过主键相互映射

<!-- secondary属性,我与Secondary的多对一 -->
<many-to-one name="secondary" class="Secondary" column="secondaryId"></many-to-one>

3、在Secondary实体类中:

private Set<ChangeInformation> changeInformations = new HashSet<ChangeInformation>();

加上get、set方法

4、在Secondary.hbm.xml文件中

<!-- changeInformations属性,我与ChangeInformation的一对多 -->
<set name="changeInformations" cascade="delete" order-by="changeTime desc" lazy="true">
<key column="secondaryId"></key>
<one-to-many class="ChangeInformation" />
</set>

二、多对多的映射关系

1、角色表Role

role.hb.xml

<!-- users属性,我与User的多对多 -->
<set name="users" table="basic_user_role" inverse="false">
<key column="roleId"></key>
<many-to-many class="User" column="userId"></many-to-many>
</set>

Role实体类中

private Set<User> users = new HashSet<User>();

加get、set方法

2、用户表User

user.hbm.xml

<!-- roles属性,我与Role的多对多 -->
<set name="roles" table="basic_user_role" inverse="false" lazy="false">
<key column="userId"></key>
<many-to-many class="Role" column="roleId"></many-to-many>
</set>

User实体类中:

private Set<Role> roles = new HashSet<Role>();

加get、set方法

三、完成映射后的调用

User user = new User();

user.setRoles(roleService.getByIds(roleIds));//给角色表的属性赋值,roleService.getByIds(roleIds)是根据角色id获取角色的实体,也可以是role的实例化对象

Role role = user.getRoles();//调用属性时还可以:user.role.roleName,即对象.属性

hibernate映射文件,实现一对多、多对一、多对多的映射关系

原文:http://www.cnblogs.com/ouyanxia/p/6590608.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!