多对一
情景:
学生表里面有 id、name、tid(外键)
教师表里有id、name
怎么查出学生表中有老师的名字?
数据库连接查询:
select s.id, s.name, t.name from teacher as t, student as s where t.id = s.tid;
查询结果:
那么mybatis中怎么实现这种多对一的复杂情况查询呢?
用到了association
1.按照 查询 嵌套处理
StudentMapper.xml(思路:子查询)
<mapper namespace="com.geng.dao.StudentMapper">
<!--query students -->
<select id="getStudentList" resultMap="StudentTeacher">
select * from mybatis.student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--complex situation-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacherList"/>
</resultMap>
<!--query teachers-->
<select id="getTeacherList" resultType="Teacher">
select * from mybatis.teacher
</select>
</mapper>
注意:这里的“Type”类型在mybatis-config.xml文件中取了别名
2.按照 结果 嵌套处理
思路:连表查询
<mapper namespace="com.geng.dao.StudentMapper">
<!--second-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid, s.name sname, t.name tname from mybatis.student s, mybatis.teacher t where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
</mapper>
查询结果:
一对多