Mybatis——多对一的处理
1.新建实体类
2.建立Mapper接口
3.建立Mapper.xml文件
4.在核心配置文件中绑定注册Mapper接口或者文件
5.测试
按照查询嵌套处理
实体类
Mapper接口
//查询所有的学生信息以及对应的老师信息
List<Student> getStudents();
Mapper.xml文件
<select id="getStudents" resultMap="StudentTeacher">
select * from student
</select>
<select id="getTeacherById" resultType="Teacher">
select * from teacher where id = #{id}
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的语句单独处理,属性是Teacher类,通过tid列,利用getTeacherById的select进行嵌套查询-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacherById"/>
</resultMap>
相当于子查询
按照结果嵌套处理
<select id="getStudents2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.id tid,t.name tname
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="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
相当于联表查询
浙公网安备 33010602011771号