首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

many-to-many(多对多联系关系)

2012-10-08 
many-to-many(多对多关联)多对多关联是常见的一种关联关系,如User与Role,一个用户可以对应多个角色,一个角

many-to-many(多对多关联)

多对多关联是常见的一种关联关系,如User与Role,一个用户可以对应多个角色,一个角色也可以对应多个用户。

要理解这个映射关系,必须了解set及many-to-many这两个标签中的相关属性。

下面以User与Role为例:

1.POJO类

User类

?Role.hbm.xml

?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)
构建了三张表,两张主表,一张中间表,并取主表主键作为中间表的外键。

?

?

热点排行