<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mybatis.mapping.class2Mapper"> <!-- 方式一: 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集 SELECT * FROM class c, teacher t,student s WHERE c.teacher_id=t.t_id AND c.C_id=s.class_id AND c.c_id=1 --> <select id="getClassId" parameterType="int" resultMap="ClassIdResultMap"> select * from class,teacher,student where class.c_id=student.class_id and class.teacher_id=teacher.t_id and c_id=#{id}; </select> <resultMap type="Classes" id="ClassIdResultMap"> <id property="id" column="c_id" /> <result property="name" column="c_name" /> <association property="teacher" javaType="Teacher" column="teacher_id"> <id property="id" column="t_id" /> <result property="name" column="t_name" /> </association> <collection property="students" ofType="Student"> <id property="id" column="s_id" /> <result property="name" column="s_name" /> </collection> </resultMap> <!-- 方式二:嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型 SELECT * FROM class WHERE c_id=1; SELECT * FROM teacher WHERE t_id=1 //1 是上一个查询得到的teacher_id的值 SELECT * FROM student WHERE class_id=1 //1是第一个查询得到的c_id字段的值 --> <select id="getClassById2" parameterType="int" resultMap="getClassById2ResultsetMap"> select * from class where c_id=#{id} </select> <resultMap type="Classes" id="getClassById2ResultsetMap"> <id property="id" column="c_id" /> <result property="name" column="c_name" /> <association property="teacher" column="teacher_id" javaType="Teacher" select="getTeacher2"></association> <collection property="students" ofType="Student" column="c_id" select="getStudents"></collection>
</resultMap> <select id="getTeacher2" parameterType="int" resultType="Teacher"> select t_id id,t_name name from teacher where t_id=#{id} </select> <select id="getStudents" parameterType="int" resultType="Student"> select s_id id,s_name name from student where class_id=#{id} </select> </mapper>