Mybatis多对一 一对多
思想:所有我们无法直接得到的结果,都需要使用ResultMap结果集映射
结果集映射,需要保证返回的对象的属性和数据库查询出来的字段一一对应。
一对多就是以以为中心在属性字段时一的老师应该做调整
多对一就是以多为中心 在属性字段时多的学生类应该做调整
我们这里有两张 表
1老师表 老师中有id name
2学生表 学生表中有id name tid(老师的id)
如何使用Mybatis查出学生表中老师的信息是问题的关键,我们无法直接得到teacher的tid所以这里就要使用ResultMap来映射。
在创建实体类的时候应该注意,在创建tid时类型应当为老师类,不能是简单的int
多对一
<resultMap id="StudentTeacher" type="student">
<result column="sid" property="id"></result>
<result column="sname" property="name"></result>
<association property="tid" javaType="teacher">
<result column="tid" property="id"></result>
<result column="tname" property="name"></result>
</association>
</resultMap>
<select id="getStudent" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.id tid,t.name tname
from student s, teacher t
where s.id=t.id
</select>
一对多
学生类正常写老师类加一个集合
<?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.xxr.mapper.TeacherMapper">
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<collection property="students" ofType="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.id tid,t.name tname
from student s, teacher t
where s.id=t.id and t.id=#{id}
</select>
</mapper>