个人白话:找个桥梁将学生信息和老师信息连接起来。通过先把两个表单都查出来,然后通过tno进行关联。即嵌套 Select 查询。也可以先把两者都连接起来再直接查询。即嵌套结果映射。
示例:查询完整的学生信息,包括老师信息。
学生表单 和 老师表单,数据库字段如下:
#学生表单
CREATE TABLE S(
sno INT PRIMARY KEY NOT NULL,
sname VARCHAR(40),
age INT,
pwd VARCHAR(60),
tno INT ,
FOREIGN KEY S(tno) REFERENCES T(tno)
);
#老师表单
CREATE TABLE T(
tno INT PRIMARY KEY NOT NULL,
tname VARCHAR(40),
age INT,
pwd VARCHAR(60)
);
java类
//学生类
public class Student {
private int sNo;
private String sName;
private int age;
private String pwd;
//难点,通过tno关联T表查询
private Teacher teacher;
//...省略实体类其他
}
老师类
public class Teacher {
private int tNo;
private String tName;
private int age;
private String pwd;
}
-
嵌套 Select 查询:通过执行另外一个 SQL 映射语句来加载期望的复杂类型。
<!-- 获取学生全部信息,包括老师。 student为数据库名--> <select id="getStudentInformation" resultMap="fromStudentGetTeacher"> SELECT sno as sNo, sname as sName, age, pwd, tno as tNo FROM student.s WHERE sno = #{sNo}; </select> <resultMap id="fromStudentGetTeacher" type="com.mcwen.pojo.Student"> <association property="teacher" column="tno" javaType="com.mcwen.pojo.Teacher" select="selectTeacher"/> </resultMap> <select id="selectTeacher" resultType="com.mcwen.pojo.Teacher"> SELECT tno as tNo, tname as tName, age, pwd FROM student.t WHERE tno = #{tNo}; </select>
-
嵌套结果映射:使用嵌套的结果映射来处理连接结果的重复子集。
<select id="getStudentInformation" resultMap="StuTeacher">
select s.sno as sNo, s.sname as sName, s.age, s.pwd, t.tno as tNo,t.tname as tName,t.age,t.pwd
from student.s,student.t
where s.tno=t.tno and s.sno=#{sNo};
</select>
<resultMap id="StuTeacher" type="com.mcwen.pojo.Student">
<result property="sNo" column="sno"/>
<result property="sName" column="sname"/>
<result property="age" column="age"/>
<result property="pwd" column="pwd"/>
<association property="teacher" column="tno" javaType="com.mcwen.pojo.Teacher" resultMap="getTeacher">
</association>
</resultMap>
<resultMap id="getTeacher" type="com.mcwen.pojo.Teacher">
<id property="tno" column="getTeacher"></id>
<result property="tNo" column="tno"></result>
<result property="tName" column="tname"></result>
<result property="age" column="age"></result>
<result property="pwd" column="pwd"></result>
</resultMap>
重点理解:
复杂属性处理(即示例中Student中包含的Teacher):使用association 处理对象,通过数据库中的关联属性,将其关联到对一个复杂类型的查询。即通过tNo,找到对应的teacher对象。