1.collection标签
说到mybatis的collection标签,我们肯定不陌生,可以通过它解决一对多的映射问题,举个例子一个用户对应多个系统权限,通过对用户表和权限表的关联查询我们可以得到好多条记录,但是用户信息这部分在多条记录中是重复的,只有权限不同,我们需要把这多条权限记录映射到这个用户之中,这个时候可以通过collection标签/association标签来解决(虽然assocation标签一般是解决一对一问题的,但它实际上也能实现我们的需求,可以通过后面的源码看出来)
1.1 相关代码和运行结果
实体类和mapper代码
@Data
public class UserDO {
private Integer userId;
private String username;
private String password;
private String nickname;
// 将用户的权限信息映射到用户中
private List<PermitDO> permitDOList;
public UserDO() {}
public UserDO(@Param("userId") Integer userId, @Param("username") String username, @Param("password") String password, @Param("nickname") String nickname) {
this.userId = userId;
this.username = username;
this.password = password;
this.nickname = nickname;
}
}
@Data
public class PermitDO {
private Integer id;
private String code;
private String name;
private NodeTypeEnum type;
private Integer pid;
}
// mybatis代码
public interface UserMapper {
UserDO getByUserId(@Param("userId") Integer userId);
}
<mapper namespace="org.apache.ibatis.study.mapper.UserMapper">
<cache readOnly="false" flushInterval="5000" size="100" blocking="false">
</cache>
<resultMap id="BaseMap" type="org.apache.ibatis.study.entity.UserDO" autoMapping="true">
<!-- user_id列用<id>标签,因为对一个用户来说,user_id肯定是唯一的 -->
<id column="user_id" jdbcType="INTEGER" property="userId" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="nickname" jdbcType="VARCHAR" property="nickname"/>
<!-- <collection> 映射多条权限记录 -->
<collection property="permitDOList"
resultMap="PermitBaseMap">
</collection>
</resultMap>
<resultMap id="PermitBaseMap" type="org.apache.ibatis.study.entity.PermitDO">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="code" jdbcType="VARCHAR" property="code"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="type" jdbcType="TINYINT" property="type"/>
<result column="pid" jdbcType="INTEGER" property="pid"/>
</resultMap&