# 多對一的處理 ###### tags: `Mybatis-查詢環境` ### 按照查詢嵌套處理 ```xml= <!-- 思路: 1.查詢所有的學生信息 2.根據查詢出來的學生的tid,尋找對應的老師 子查詢 --> <select id="getStudent" resultMap="StudentTeacher"> select * from student; </select> <!--說明:1.student中有teacher字段,不是普通java對象(pojo),因此需要告訴mybatis這個對象從哪來 (就是這麼才能查到並初始化一個對象) 2.在查詢學生的語句中,寫上resultMap來告訴mybatis我的非pojo字段來自名為studentTeacher的結果映射 3.在StudentTeacher結果映射中,我們寫出Teacher怎麼來的,property寫出非pojo字段,select告訴mybatis 我是通過下邊的getTeacher獲得teacher 4.column標識getTeacher中缺省參數id的來源是student的tid --> <resultMap id="StudentTeacher" type="Student"> <result property="id" column="id"/> <result property="name" column="name"/> <!--複雜的屬性,我們需要單獨處理 對象:association 集合:collection --> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id = #{id} </select> ``` ### 按照結果嵌套處理 ```xml= <select id="getStudent2" resultMap="StudentTeacher2"> select s.id sid,s.name sname,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="name" column="tname"/> </association> </resultMap> ``` 回顧MySQL多對一查詢方式: * 子查詢 * 連表查詢