Mybatis 一对多 多对一 联表查询代码
1、多对一处理
多个学生 --------> 一个老师
1. 按照 ’ 查询 ’ 嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="teacher">
select * from teacher where id = #{id}
</select>
2. 按照 ’ 结果 ’ 嵌套处理【推荐】
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid, s,name sname, t.name
from student s, teacher t
where s.tid = t.id
</select>
<resultMap id="StudentTeacher2" type="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
2、一对多处理
一个老师 --------> 多个学生
1. 按照 ’ 查询 ’ 嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid = #{tid}
</select>
2. 按照 ’ 结果 ’ 嵌套处理【推荐】
<select id="getTeacher" resultMap="StudentTeacher">
select s.id sid, s.name sname, t.name tname, t.id tid from student s, teacher t
where s.tid = t.id and tid = #{tid}
</select>
<resultMap id="StudentTeacher" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
|