需求:查询所有学生信息,以及对应的老师信息
sql语句:select s.id,s.name,t.id from student s where t.id=(select id from teacher )
第一步:编写mapper接口
public interface StudentMapper {
?
//需求:查询所有学生信息,以及对应的老师信息
List<Student> findAllStudents()throws Exception;
}
public interface TeacherMapper {
?
Teacher findTeacherById(Integer id)throws Exception;
}
第二步:编写StudentMapper.xml配置文件(关键)
关键一:我们需要先查出学生表的所有信息
关键二:通过id查出教师表的相应信息,因为我们学生实体类是关联到教师类的
关键三:通过ResultMap做映射处理 前两个字段就正常写,复杂属性通过官网我们知道要使用association标签,需要制定类型以及sql语句 也可以说是套娃学生sql套teacher的sql
第三步:编写测试
---------------------------------------测试成功-----------------------------------------
sql语句 select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id
其他都与按照查询嵌套处理方式一致,这里就写关键处
编写StudentMapper.xml配置文件
<resultMap id="studentMap" type="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"></result>
</association>
</resultMap>
?
<select id="findAllStudents" resultMap="studentMap">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id
</select>
原文:https://www.cnblogs.com/xuan-study/p/13325247.html