场景
在查询用户的角色列表时,用户与角色是一对多的关系,查询的SQL结果集一般都是多条,我们定义的映射关系一般是角色是一个List
解决方法
示例数据表
create table mall_admin_user_role
(
id bigint auto_increment
primary key,
uid bigint not null,
role_id int not null
);
示例实体
public class UserRoleModel {
private Long uid;
private List<Integer> roleIds;
}
示例map映射
<select id="getRolesByUid" resultMap="userRoleMap">
select * from mall_admin_user_role where uid=#{uid}
</select>
<resultMap id="userRoleMap" type="UserRoleModel">
<result property="uid" column="uid"/>
<collection property="roleIds" javaType="java.util.List" ofType="java.lang.Integer">
<result column="role_id" />
</collection>
</resultMap>
关键是collection标签的javaType和ofType,因为示例中的List元素是基本数据类型,所以使用ofType设置具体的基本数据类型