按照查询嵌套处理(稍微复杂点)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatisstudy.dao.StudentMapper">
<!--
思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid 寻找对应的老师
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student
<!-- select s.id,s.name,t.name from student s,teacher t where s.tid=t.id-->
</select>
<resultMap id="StudentTeacher" type="com.mybatisstudy.pojo.Student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<!--复杂的属性 需要单独处理
对象:association
集合:collection
-->
<association property="teacher" column="tid" javaType="com.mybatisstudy.pojo.Teacher" select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="com.mybatisstudy.pojo.Teacher">
select * from teacher where id = #{id}
</select>
</mapper>
按照结果嵌套处理(偏简单,推荐使用)
<!--按照结果嵌套处理-->
<select id="getStudentNew" resultMap="StudentNew">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id;
</select>
<resultMap id="StudentNew" type="com.mybatisstudy.pojo.Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="com.mybatisstudy.pojo.Teacher">
<result property="name" column="tname"></result>
</association>
</resultMap>
Mysql多对一查询方式:
- 子查询
- 联表查询