1.使用 resultMap 实现关联单个对象(联合查询方式)
<resultMap type="Student" id="stuMap1"> <id column="sid" property="id"/> <result column="sname" property="name"/> <result column="age" property="age"/> <result column="tid" property="tid"/> <association property="teacher" javaType="Teacher" > <id column="tid" property="id"/> <result column="tname" property="name"/> </association> </resultMap> <select id="selAll1" resultMap="stuMap1"> select s.id sid,s.name sname,age age,t.id tid,t.name tname FROM student s left outer join teacher t on s.tid=t.id </select>
注意id为selAll1的select标签与下面id为selAll的select标签的区别
<resultMap type="student" id="stuMap"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> <result column="tid" property="tid"/> <association property="teacher" javaType="Teacher" column="tid" select="com.xxx.mapper.TeacherMapper.selById" > </association> </resultMap> <select id="selAll" resultMap="stuMap"> select * from student </select>
第一中是联合查询,第二中不是,是先查询每一个学生,然后再根据学生的tid去查询老师,第二种实现效率低