多对多关系映射最大的特点就是生成了一张中间表,多对多关系分为单向多对多和双向多对多
单向多对多在一方加入一个set,在配置文件中需指定中间表,同时也可以指定cascade,设置了cascade="all"后,
在保存Role的时候,就将User同时保存了,
配置文件
<class name="Role" table="tb_role">
<id name="roleId">
<generator class="native"></generator>
</id>
<property name="roleName"></property>
</class>
<class name="User" table="tb_user">
<id name="userId">
<generator class="native"></generator>
</id>
<property name="userName"></property>
<set name="roles" table="tb_user_role">
<key column="userId"></key>
<many-to-many class="Role" column="roleId" />
</set>
</class>
<set name="roles" table="tb_user_role">
<key column="userId">
</key>
<many-to-many class="Role" column="roleId" />
</set>
在tb_user_role表中,User类中,根据roles集合中的数据,生成数据,其中userId为主键
持久化类文件
public class Role {
private int roleId;
private String roleName;
...
get,set方法
...
}
public class User {
private int userId;
private String userName;
private Set<Role> roles;
...
get,set方法
...
}
双向多对多
<class name="User" table="tb_user">
<id name="userId">
<generator class="native"></generator>
</id>
<property name="userName"></property>
<set name="roles" table="tb_user_role">
<key column="userId"></key>
<many-to-many class="Role" column="roleId" />
</set>
</class>
<class name="Role" table="tb_role">
<id name="roleId">
<generator class="native"></generator>
</id>
<property name="roleName"></property>
<set name="users" table="tb_user_role">
<key column="roleId"></key>
<many-to-many class="User" column="userId" />
</set>
</class>
持久化类文件,需要在两方都有set属性
public class User {
private int userId;
private String userName;
private Set<Role> roles;
...
get,set方法
...
}
public class Role {
private int roleId;
private String roleName;
private Set<User> users;
...
get,set方法
...
}