联合(association)元素用来处理“一对一”的关系,比如简单的学生和老师的关系,我们假设现在一个老师有多个学生,但是一个学生只有一个老师,实际列子使用的数据是张三丰和武当七侠,王重阳和全真七子
先看看数据,student表:
teacher表:
再来看第一种写法:
<resultMap id="studentResult" type="com.zengyg.myibatis.dto.StudentInfo">
<id property="studentId" column="student_id" />
<result property="name" column="name" />
<result property="sex" column="sex" />
<association property="teacher" column="teacherId_s"
javaType="com.zengyg.myibatis.dto.TeacherInfo" select="selectTeacher" />
</resultMap>
<select id="selectTeacher" parameterType="int"
resultType="com.zengyg.myibatis.dto.TeacherInfo">
select teacher_id as teacherId ,name ,sex
from teacher
where
teacher_id = #{teacherId}
</select>
<select id="queryById" parameterType="int" resultMap="studentResult">
select student_id as studentId ,name ,sex,teacher_id as teacherId_s
from student
where student_id = #{studentId}
</select>
这是子查询的方式,我们用一个select语句来加载学生,其中的column如果要传入多个值,可以使用column= ”{prop1=col1,prop2=col2}” 这样的语法,设置多个列名传入到嵌套语句,这种方式的优点是比较直观,简单易懂,很容易理解,缺点是对大数据集或者列表可能造成N+1的问题,概
要地说,N+1问题会这样产生:
- 你执行一个单条语句去获取一个列表记录。(“+1”)
- 对每一条记录,再去执行一个select 语句去加载每一条记录的详细(“N”)
这个问题会可能会造成成千上万的语句执行,后果无法预料,所以这种方式在可预知结果集(如用ID查询)时推荐使用,但是不确定查询结果集时推荐使用另外一种方式:
<resultMap id="studentResultTeacher" type="com.zengyg.myibatis.dto.StudentInfo">
<id property="studentId" column="student_id" />
<result property="name" column="name" />
<result property="sex" column="sex" />
<result property="teacherId" column="teacherId_s" />
<association property="teacher" column="teacherId_s"
javaType="com.zengyg.myibatis.dto.TeacherInfo">
<id property="teacherId" column="teacherId_t" />
<result property="name" column="teacher_name" />
<result property="sex" column="teacher_sex" />
</association>
</resultMap>
<select id="queryByTeacherId" parameterType="int" resultMap="studentResultTeacher">
select
s.student_id ,
s.name ,
s.sex,
s.teacher_id as teacherId_s,
t.teacher_id as teacherId_t,
t.name as teacher_name,
t.sex as teacher_sex
From student s left outer join teacher t on s.teacher_id = t.teacher_id
where s.teacher_id = #{teacherId}
</select>
这种外连接的方式确保只执行一次查询。
另外非常重要的是id 元素是嵌套映射中非常重要的角色。你需要指定一个或更多的属性用来标记结果。如果你没有这么做,MyBatis 也可能会正常运行,但是却会付出惨重的性能损耗。尽量用数量少的列来唯一标
识结果,使用主键是个好的选择。
以上完整代码地址:https://git.oschina.net/zengyg/J2EEAPIStudy.git