多對一、一對多
阿新 • • 發佈:2021-01-13
技術標籤:Mybatis
環境搭建
1匯入lombok
2.新建實體類 Teacher Student
3.建立Mapper介面
4.建立Mapper.xml
5.在核心配置檔案中繫結介面
6.測實是否能夠執行
多對一
實體類
private int id;
private String name;
//學生需要關聯一個老師
private Teacher teacher;
private int id;
private String name;
按照查詢巢狀處理
<!-- 思路: 1.查詢所有的學生資訊 2.根據查詢出來的學生的tid,尋找對應的老師 --> <select id="getStudent" resultMap="StudentTeacher"> select * from student </select> <select id="getTeacher" resultType="Teacher"> select * from teacher where id =#{id} </select> <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="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多對一查詢
1.子查詢
2.聯表查詢
一對多
按照結果巢狀處理
<!-- 按結果巢狀查詢--> <select id="getTeacher" resultMap="TeacherStudent"> select s.id sid ,s.name sname,t.name tname,t.id tid from teacher t,student s where s.tid=t.id and t.id=#{tid} </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <!-- javatype=“”指定屬性的型別 集合中的泛型資訊,我們使用ofType--> <collection property="students" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap>
按照查詢巢狀處理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select *from student where tid=#{tid}
</select>
1.關聯-association【多對一】
2.集合-collection【一對多】
1.JavaType 用來指定實體類中屬性的型別
2.ofType 用來指定對映到List或者集合中的pojo型別,泛式中的約束型別
保證sql的可讀性 儘量保證能夠通俗易懂
注意一對多和多對一中,屬性名和欄位的問題