MyBatis中association的基本使用方法
通過association對兩表進行聯(lián)表查詢
student表屬性如下
teacher表屬性如下
按照查詢嵌套處理
- 關(guān)于需求的SQL稍微有點復(fù)雜時,可以打開右側(cè)查詢框進行語句的編寫執(zhí)行。
當(dāng)使用以下時,查詢出來存在問題
<select id="getStudentTeacher" resultType="Student" > select s.id,s.name,t.id, t.name from student s, teacher t where s.tid = t.id </select>
思路:
- 查詢所有的學(xué)生信息
- 根據(jù)查詢出來的學(xué)生tid,尋找對應(yīng)的老師
利用結(jié)果集映射,聯(lián)系起來
編寫接口
// 查詢所有的學(xué)生信息以及對應(yīng)的老師信息 List<Student> getStudent();
編寫mapper配置文件
<select id="getStudent" resultMap = "StudentTeacher" > select * from student </select> <resultMap id="StudentTeacher" type="Student"> <result property="id" column="id" /> <result property="name" column="name" /> <!-- 復(fù)雜的屬性需要單獨處理 對象:association 集合:collection --> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id = #{nid} </select>
測試得到結(jié)果
結(jié)果中嵌套了結(jié)果
一些注意問題:
- teacher中的id的傳遞是根據(jù)student中得到的tid,將tid傳給id,因此#{}中取什么名字都可以。
- association將實體類的teacher屬性對應(yīng)上一個結(jié)果,這個結(jié)果是將tid作為參數(shù)參與下一條sql語句產(chǎn)生的。
按照結(jié)果嵌套處理
- 個人認為這種方法更直觀
- 正確的查詢
<!--按照結(jié)果嵌套處理--> <select id="getStudent2" resultMap="StudentTeacher2" > select s.id sid,s.name sname,t.id tid, 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="id" column="tid" /> <result property="name" column="tname" /> </association> </resultMap>
查詢出來的需要展現(xiàn)的結(jié)果都應(yīng)該在resultMap中進行定義,否則會以默認值進行展示如下,在resultMap中注釋掉tid和sname后,執(zhí)行的結(jié)果
總結(jié)
到此這篇關(guān)于MyBatis中association基本使用的文章就介紹到這了,更多相關(guān)MyBatis association使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Mybatis中collection和association的使用區(qū)別詳解
- mybatis利用association或collection傳遞多參數(shù)子查詢
- Mybatis之a(chǎn)ssociation和collection用法
- 在Mybatis中association標簽多層嵌套的問題
- mybatis中一對一關(guān)系association標簽的使用
- mybatis的association傳遞參數(shù)問題示例
- Mybatis中一對多(collection)和一對一(association)的組合查詢使用
- MyBatis的collection和association的使用解讀
- mybatis中association標簽的使用解讀
- MyBatis使用嵌套查詢collection和association的實現(xiàn)
- Mybatis的association使用子查詢結(jié)果錯誤的問題解決
相關(guān)文章
SpringCloud網(wǎng)關(guān)組件zuul實例解析
這篇文章主要介紹了SpringCloud網(wǎng)關(guān)組件zuul實例解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03SpringBoot靜態(tài)資源css,js,img配置方案
這篇文章主要介紹了SpringBoot靜態(tài)資源css,js,img配置方案,下文給大家分享了三種解決方案,需要的朋友可以參考下2017-07-07IntelliJ IDEA報錯Error:java: Compilation failed: internal java
今天小編就為大家分享一篇關(guān)于IntelliJ IDEA報錯Error:java: Compilation failed: internal java compiler error的解決辦法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10