多对多关联是常见的一种关联关系,如User与Role,一个用户可以对应多个角色,一个角色也可以对应多个用户。
要理解这个映射关系,必须了解set及many-to-many这两个标签中的相关属性。
下面以User与Role为例:
1.POJO类
User类
public class User {
private int userId;
private String userName;
private Set roles;
//...set/get
}
Role类
public class Role {
private int roleId;
private String roleName;
private Set users;
//...get/set
}
2.映射文件
User.hbm.xml
<hibernate-mapping package="org.zengge.hibernate.manytomany.pojo">
<class name="User" table="t_user">
<id name="userId" type="integer">
<generator class="identity"></generator>
</id>
<property name="userName" type="string" ></property>
<set name="roles" table="t_role_user">
<key column="userId"/>
<!-- key定义集合表到其拥有表的外键 -->
<many-to-many class="Role" column="roleId"/>
<!-- many-to-many 集合表到该元素的外键 -->
</set>
</class>
</hibernate-mapping>
Role.hbm.xml
<hibernate-mapping package="org.zengge.hibernate.manytomany.pojo">
<class name="Role" table="t_role">
<id name="roleId" type="integer">
<generator class="identity"></generator>
</id>
<property name="roleName" type="string" ></property>
<set name="users" table="t_role_user">
<key column="roleId"/>
<!-- key中的 property-ref用于指定主非键的列作为参考外键,也就是说默认情况下会用主表的主键作为
集合表的外键,在这里就是默认为t_role的主键作为t_role_user的外键
-->
<many-to-many class="User" column="userId" />
<!--
column(必需): 这个元素的外键关键字段名
property-ref: 用于指定关联类(User)连接到外键的属性,即那个字段与集合表t_role_user中的
userId关联,如果没指定就默认为关联类(User)的主键
-->
</set>
<!--
使用<key>元素来申明从集合表到其拥有者类的表
(from the collection table to the table of the owning class)的外键关键字。
<key column="column_name"/>
column(必需):外键字段的名称
-->
</class>
</hibernate-mapping>
set用于映射集合,name表示属性名称,table表示集合对应的集合表
key:用于定义连接表中的外键,默认引用主表中的主键作外键
column表示外键名称
property-ref,上面有讲
对于key与many-to-many的作用就在于定义好集合表中的外键名称,及外键引用的是主表中的那个字段.
3.测试
导出表
public static void exportSchema(){
SchemaExport schemaExport = new SchemaExport(configuration);
schemaExport.create(true, true);
}
结果为
create table t_role (roleId integer not null auto_increment, roleName varchar(255), primary key (roleId))
create table t_role_user (userId integer not null, roleId integer not null, primary key (roleId, userId))
create table t_user (userId integer not null auto_increment, userName varchar(255), primary key (userId))
alter table t_role_user add index FK32E9F7E9217E219A (roleId), add constraint FK32E9F7E9217E219A foreign key (roleId) references t_role (roleId)
alter table t_role_user add index FK32E9F7E926D37704 (userId), add constraint FK32E9F7E926D37704 foreign key (userId) references t_user (userId)
构建了三张表,两张主表,一张中间表,并取主表主键作为中间表的外键。