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

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

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,即对象.属性

原文地址:https://www.cnblogs.com/ouyanxia/p/6590608.html