# 一對多的處理 ###### tags: `Mybatis-查詢環境` 比如:一個老師擁有多個學生! 對於老師而言,就是一對多的關係 1.環境搭建,和多對一一樣 2.實體類 ```java= @Data public class Student { private int id; private String name; private int tid; } ``` ```java= @Data public class Teacher { private int id; private String name; //一個老師擁有多個學生 private List<Student> students; } ``` ### 按結果嵌套查詢 ```xml= <!--按結果嵌套查詢 --> <select id="getTeacher" resultMap="TeacherStudent"> select s.id sid, s.name sname, t.name tname, t.id tid from student s, teacher t where s.tid = t.id and t.id = #{tid}; </select> <resultMap id="TeacherStudent" type="com.kuang.pojo.Teacher"> <result property="id" column="tid"></result> <result property="name" column="tname"></result> <!--複雜的屬性,我們需要單獨處理 對象:association 集合:collection javaType="" 指定屬性的類型 集合中的泛型信息,我們使用ofType獲取 --> <collection property="studentList" ofType="com.kuang.pojo.Student"> <result property="id" column="sid"></result> <result property="name" column="sname"></result> </collection> </resultMap> ``` ### 按照查詢嵌套處理 ```xml= <select id="getTeacher2" resultMap="TeacherStudent2"> select * from mybatis.teacher where id = #{tid}; </select> <resultMap id="TeacherStudent2" type="com.kuang.pojo.Teacher"> <!--javaType="ArrayList":集合類型 ofType:泛型--> <collection property="studentList" javaType="ArrayList" ofType="com.kuang.pojo.Student" select="getStudentByTeacherId" column="id"/> </resultMap> <select id="getStudentByTeacherId" resultType="com.kuang.pojo.Student"> select * from mybatis.student where tid = #{tid}; </select> ``` ### 小結 1. 關聯-association【多對一】 2. 集合-collection【一對多】 3. javaType & ofType: 4. javaType:用來指定實體類中屬性的類型 -> List<Student>的list類型 5. ofType:用來指定映射到List或者集合中的pojo類型,泛型中的約束類型 -> List<Student>的泛型(Student ### 注意點 * 保證SQL的可讀性,盡量保證通俗易懂 * 注意一對多和多對一中,屬性名和字段的問題 * 如果問題不好排查錯誤,可以使用日誌 ### 面試高頻問題 * MySQL引擎 * InnoDB底層原理 * 索引 * 索引優化
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up