Mybatis源码分析(十二) – 关联查询之一对多

1. collection 支持的属性以及属性的作用和 association 完全相同
2. mybatis会根据id标签,进行字段的合并,合理配置好ID标签可以提高处理的效率;

一对多 嵌套结果

private List<TJobHistory> jobs ;

示例代码

<select id="selectUserJobs1" resultMap="userAndJobs1">
select
a.id,
a.user_name,
a.real_name,
a.sex,
a.mobile,
b.comp_name,
b.years,
b.title
from t_user a,
t_job_history b
where a.id = b.user_id

</select>
<resultMap id="userAndJobs1" extends="BaseResultMap" type="TUser">
<collection property="jobs"
ofType="com.caojiulu.mybatis.entity.TJobHistory" >
<result column="comp_name" property="compName" jdbcType="VARCHAR" />
<result column="years" property="years" jdbcType="INTEGER" />
<result column="title" property="title" jdbcType="VARCHAR" />
</collection>
</resultMap>

一对多 嵌套查询

示例代码

<select id="selectUserJobs2" resultMap="userAndJobs2">
select
a.id,
a.user_name,
a.real_name,
a.sex,
a.mobile
from t_user a
</select>
<resultMap id="userAndJobs2" extends="BaseResultMap" type="TUser">
<collection property="jobs" fetchType="lazy" column="id"
select="com.caojiulu.mybatis.mapper.TJobHistoryMapper.selectByUserId" />
</resultMap>