MyBatis中association的基本使用方法
通過association對兩表進行聯(lián)表查詢
student表屬性如下

teacher表屬性如下

按照查詢嵌套處理
- 關于需求的SQL稍微有點復雜時,可以打開右側查詢框進行語句的編寫執(zhí)行。
當使用以下時,查詢出來存在問題
<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>

思路:
- 查詢所有的學生信息
- 根據(jù)查詢出來的學生tid,尋找對應的老師
利用結果集映射,聯(lián)系起來
編寫接口
// 查詢所有的學生信息以及對應的老師信息 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" />
<!-- 復雜的屬性需要單獨處理
對象:association
集合:collection
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{nid}
</select>
測試得到結果
結果中嵌套了結果

一些注意問題:

- teacher中的id的傳遞是根據(jù)student中得到的tid,將tid傳給id,因此#{}中取什么名字都可以。
- association將實體類的teacher屬性對應上一個結果,這個結果是將tid作為參數(shù)參與下一條sql語句產(chǎn)生的。
按照結果嵌套處理
- 個人認為這種方法更直觀
- 正確的查詢
<!--按照結果嵌套處理-->
<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)的結果都應該在resultMap中進行定義,否則會以默認值進行展示如下,在resultMap中注釋掉tid和sname后,執(zhí)行的結果

總結
到此這篇關于MyBatis中association基本使用的文章就介紹到這了,更多相關MyBatis association使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Mybatis中collection和association的使用區(qū)別詳解
- mybatis利用association或collection傳遞多參數(shù)子查詢
- Mybatis之a(chǎn)ssociation和collection用法
- 在Mybatis中association標簽多層嵌套的問題
- mybatis中一對一關系association標簽的使用
- mybatis的association傳遞參數(shù)問題示例
- Mybatis中一對多(collection)和一對一(association)的組合查詢使用
- MyBatis的collection和association的使用解讀
- mybatis中association標簽的使用解讀
- MyBatis使用嵌套查詢collection和association的實現(xiàn)
- Mybatis的association使用子查詢結果錯誤的問題解決
相關文章
SpringBoot靜態(tài)資源css,js,img配置方案
這篇文章主要介紹了SpringBoot靜態(tài)資源css,js,img配置方案,下文給大家分享了三種解決方案,需要的朋友可以參考下2017-07-07
IntelliJ IDEA報錯Error:java: Compilation failed: internal java
今天小編就為大家分享一篇關于IntelliJ IDEA報錯Error:java: Compilation failed: internal java compiler error的解決辦法,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10

