多对一查询
1、实体类
Student实体类:
public class Student {
private int id;
private String name;
private Teacher teacher;//对象属性
}
Teacheer 实体类:
public class Teacher {
private int id;
private String name;
2、Mybatis配置文件mybatis-config注册Mapper:
<mappers>
<mapper class="com.kuang.dao.TeacherMapper"/>
<mapper class="com.kuang.dao.StudentMapper"/>
</mappers>
3、接口
StudentMapper
public interface StudentMapper {
// 学生--老师
public List<Student> getStudens();
}
4、StudentMapper.xml写sql:
<select id="getStudens" resultType="Student">
select * from student
</select>
5、测试:
public void selectStudent() {
SqlSession session = MybatisUtils.getSession();//获取
StudentMapper m = session.getMapper(StudentMapper.class);
List<Student> stu = m.getStudens();
System.out.println(stu);
for (Student s : stu) {
System.out.println
("学生数据遍历===" + s);
}
}
运行结果:
teacher=null
这个查询结果中未查询到teacher的数据
优化
1、按照查询嵌套处理StudentMapper.xm后:
1、
<select id="getStudens" resultMap="studentTeacher">
select * from student
</select>
2、
<resultMap id="studentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/
</resultMap>
3、
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id};
</select>
测试结果:
学生数据遍历=Student(id=1, name=小明, teacher=Teacher(id=1, name=秦老师))
学生数据遍历=Student(id=2, name=小红, teacher=Teacher(id=1, name=秦老师))
学生数据遍历=Student(id=3, name=小张, teacher=Teacher(id=1, name=秦老师))
学生数据遍历=Student(id=4, name=小李, teacher=Teacher(id=1, name=秦老师))
学生数据遍历===Student(id=5, name=小王, teacher=Teacher(id=1, name=秦老师
resultMap结果集进行复杂查询的处理association :对象处理
思路:1.查询学生表数据,2.根据tid查询学生对应的老师数据-----》子查询原理
2、按照结果嵌套处理StudentMapper.xm后:
<select id="getStudens1" resultMap="map">
select s.id sid,s.name sname,
t.name tname from student s,teacher t
</select>
<resultMap id="map" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
测试结果:
学生数据遍历=Student(id=1, name=小明, teacher=Teacher(id=0, name=秦老师))
学生数据遍历=Student(id=2, name=小红, teacher=Teacher(id=0, name=秦老师))
学生数据遍历=Student(id=3, name=小张, teacher=Teacher(id=0, name=秦老师))
学生数据遍历=Student(id=4, name=小李, teacher=Teacher(id=0, name=秦老师))
学生数据遍历===Student(id=5, name=小王, teacher=Teacher(id=0, name=秦老师))
mybatis 多对一查询
1.按照查询嵌套处理-----子查询
2.按照结果嵌套处理-----连表查询