多对一处理
一、查询嵌套查询
<!-- 1、查询所有的学生信息 2、根据查询出来的学生的tid,查询对应的老师 --> <select id="getStudent" resultMap="StudentTeacher"> select * from mybatis.student </select> <resultMap id="StudentTeacher" type="stu"> <result property="id" column="id"/> <result property="name" column="name"/> <!-- 复杂的部分需要单独处理 对象:association 集合:collection --> <!-- peoperty是实体类中的属性;tid是对应的数据库中的属性; javaType是查询结果的实体类;select是嵌套查询的sql语句的名称--> <association property="teacher" column="tid" javaType="tea" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="tea"> select * from mybatis.teacher where id = #{id} </select>
二、按照查询结果查询
<!--按照查询结构嵌套--> <select id="getStudent2" resultMap="StudentTea"> select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id; </select> <resultMap id="StudentTea" type="stu"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="tea"> <result property="id" column="id"/> <result property="name" column="tname"/> </association> </resultMap>