<?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"><mappernamespace="com.hcz.dao.StudentDao"><!--=========================方式1:(联表查询)按结果嵌套处理=============================--><selectid="selectAllStudent"resultMap="StudentTeacher">
select s.id as sid,s.name as sname,t.name as tname
from student s,teacher t
where s.tid=t.id;
</select><resultMapid="StudentTeacher"type="Student"><idproperty="id"column="sid"/><resultproperty="name"column="sname"/><!--复杂的属性,我们需要单独处理
对象:association
集合:collection
--><associationproperty="teacher"javaType="Teacher"><resultproperty="name"column="tname"/></association></resultMap><!--=========================方式2:(子查询)按查询嵌套处理=============================--><!--
1、查询所有的学生信息
2、根据查询出来的学生tid,寻找对应的老师
--><selectid="selectAllStudent2"resultMap="StudentTeacher2">
select * from student
</select><resultMapid="StudentTeacher2"type="Student"><idproperty="id"column="id"/><resultproperty="name"column="name"/><!--复杂的属性,我们需要单独处理
对象:association 【多对一】
集合:collection 【一对多】
javaType:用来指定实体类中属性的类型
ofType:用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
--><associationproperty="teacher"column="tid"javaType="Teacher"select="selectAllTeacher"/></resultMap><selectid="selectAllTeacher"resultType="Teacher">
select * from teacher where id=#{id}
</select></mapper>
<?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"><mappernamespace="com.hcz.dao.TeacherDao"><!--按结果嵌套查询--><selectid="selectAllTeacher"resultMap="TeacherStudent">
select s.id as sid,s.name as sname,t.name as tname,t.id as tid
from student s, teacher t
where s.tid = t.id and t.id=#{tid}
</select><resultMapid="TeacherStudent"type="Teacher"><idproperty="id"column="tid"/><resultproperty="name"column="tname"/><!--复杂的属性,我们需要单独处理
对象:association 【多对一】
集合:collection 【一对多】
集合中的泛型信息使用ofType获取
javaType:用来指定实体类中属性的类型
ofType:用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
--><collectionproperty="students"ofType="Student"><idproperty="id"column="sid"/><resultproperty="name"column="sname"/><resultproperty="tid"column="tid"/></collection></resultMap><!--=======================================================--><selectid="selectAllTeacher2"resultMap="TeacherStudent2">
select * from teacher where id = #{tid}
</select><resultMapid="TeacherStudent2"type="Teacher"><collectionproperty="students"column="id"javaType="ArrayList"ofType="Student"select="selectStudentByTeacherId"/></resultMap><selectid="selectStudentByTeacherId"resultType="Student">
select * from student where tid = #{tid}
</select></mapper>