先决条件
- 多对多需要一种中间表建立连接关系
- 多对多关系是由两个一对多关系组成的,一对多可以也可以用两种方式实现
嵌套结果
Mapper 接口
List<TUser> selectUserRole();
Mapper XML配置
<select id="selectUserRole" resultMap="userRoleInfo">
select a.id,
a.userName,
a.realName,
a.sex,
a.mobile,
a.note,
b.role_id,
c.role_name,
c.note role_note
from t_user a,
t_user_role b,
t_role c
where a.id = b.user_id AND
b.role_id = c.id
</select>
t_user_role 就是中间表,只有两列,user_id、role_id
嵌套查询
Mapper 接口
List<TRole> selectRoleandUsers();
Mapper XML配置
<resultMap id="RoleandUsers" type="TRole" extends="BaseResultMap">
<collection property="users" fetchType="lazy" column="id" select="com.enjoylearning.mybatis.mapper.TUserMapper.selectUserByRoleId"></collection>
</resultMap>
<select id="selectRoleandUsers" resultMap="RoleandUsers">
select
<include refid="Base_Column_List" />
from t_role
</select>