MyBatis中association的基本使用方法
通過association對(duì)兩表進(jìn)行聯(lián)表查詢
student表屬性如下
teacher表屬性如下
按照查詢嵌套處理
- 關(guān)于需求的SQL稍微有點(diǎn)復(fù)雜時(shí),可以打開右側(cè)查詢框進(jìn)行語句的編寫執(zhí)行。
當(dāng)使用以下時(shí),查詢出來存在問題
<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,尋找對(duì)應(yīng)的老師
利用結(jié)果集映射,聯(lián)系起來
編寫接口
// 查詢所有的學(xué)生信息以及對(duì)應(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ù)雜的屬性需要單獨(dú)處理 對(duì)象:association 集合:collection --> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id = #{nid} </select>
測(cè)試得到結(jié)果
結(jié)果中嵌套了結(jié)果
一些注意問題:
- teacher中的id的傳遞是根據(jù)student中得到的tid,將tid傳給id,因此#{}中取什么名字都可以。
- association將實(shí)體類的teacher屬性對(duì)應(yīng)上一個(gè)結(jié)果,這個(gè)結(jié)果是將tid作為參數(shù)參與下一條sql語句產(chǎn)生的。
按照結(jié)果嵌套處理
- 個(gè)人認(rèn)為這種方法更直觀
- 正確的查詢
<!--按照結(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中進(jìn)行定義,否則會(huì)以默認(rèn)值進(jìn)行展示如下,在resultMap中注釋掉tid和sname后,執(zhí)行的結(jié)果
總結(jié)
到此這篇關(guān)于MyBatis中association基本使用的文章就介紹到這了,更多相關(guān)MyBatis association使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java編程創(chuàng)建型設(shè)計(jì)模式工廠方法模式示例詳解
這篇文章主要為大家介紹了java編程創(chuàng)建型設(shè)計(jì)模式之工廠方法模式的創(chuàng)建及案例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-02-02SpringMVC中@Valid不起效BindingResult讀取不到Error信息
在寫SpringMVC項(xiàng)目時(shí),由于要對(duì)表單數(shù)據(jù)進(jìn)行校驗(yàn),需要使用@Valid進(jìn)行校驗(yàn),但是在進(jìn)行數(shù)據(jù)校驗(yàn)時(shí),BindingResult對(duì)象無法攔截非法表單數(shù)據(jù),result.hasErrors()無論怎么輸入都會(huì)返回false,本文詳細(xì)的介紹一下解決方法2021-09-09Java基于redis和mysql實(shí)現(xiàn)簡(jiǎn)單的秒殺(附demo)
這篇文章主要介紹了Java基于redis和mysql實(shí)現(xiàn)簡(jiǎn)單的秒殺(附demo),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02動(dòng)態(tài)更改Spring定時(shí)任務(wù)Cron表達(dá)式的優(yōu)雅方案實(shí)例詳解
spring定時(shí)器非常強(qiáng)大,但是有時(shí)候我們需要在不需要重啟應(yīng)用就可以動(dòng)態(tài)的改變Cron表達(dá)式的值,下面這篇文章主要給大家介紹了關(guān)于動(dòng)態(tài)更改Spring定時(shí)任務(wù)Cron表達(dá)式的優(yōu)雅方案,需要的朋友可以參考下2022-12-12