七、MyBatis教程之四多表关系的实现
在MyBatis中,多表關(guān)系沒(méi)有像Hibernate中體現(xiàn)的那么明顯,關(guān)系型數(shù)據(jù)庫(kù)表與表之間的關(guān)系主要有:
1、一對(duì)一關(guān)系
賬戶表-----賬戶詳情表
2、多對(duì)一關(guān)系
學(xué)生和班級(jí)
3、一對(duì)多關(guān)系
班級(jí)和學(xué)生
4、多對(duì)多關(guān)系
學(xué)生和課程
而在myBatis中只需記得2個(gè)標(biāo)簽即可實(shí)現(xiàn)多表關(guān)系:
1、association標(biāo)記一對(duì)一或多對(duì)一
association其實(shí)就是標(biāo)記當(dāng)前的屬性是一個(gè)對(duì)象,一般可用于一對(duì)一或多對(duì)一
<!—實(shí)現(xiàn)兩張表的一對(duì)一關(guān)系查詢映射 --> <select id=”query” resultMap=”ws2”> select w.*,h.id husid,h.name hname,h,age hage from tb_wife w left join tb_husband h on w.hid=h.id </select> <resultMap type=”Wife” id=”ws2”> <id property=”id” column=”id”/> <result property=”name” column=”name”/> <result property=”hobby” column=”hobby”/> <!—嵌套對(duì)象,通過(guò)聯(lián)結(jié)查詢獲取結(jié)果 --> <association property=”husband” javaType=”Husband”> <id property=”id” column=”husid”/> <result property=”name” column=”hname”/> <result property=”age” column=”hage”/> </association> </resultMap> association標(biāo)記一對(duì)一或多對(duì)一一對(duì)一可以,多對(duì)一一樣,其中javaType標(biāo)記的屬性的數(shù)據(jù)類(lèi)型,不可省略。
?
2、collection實(shí)現(xiàn)一對(duì)多或多對(duì)多
該標(biāo)簽標(biāo)記當(dāng)前屬性是一個(gè)集合,內(nèi)容通過(guò)SQL查詢而來(lái)。
下面配置體現(xiàn)一對(duì)多的關(guān)系實(shí)現(xiàn):
<select id=”query1” resultMap=”myhs2”>select h.*,c.id cid,c.name cname,c.infant from tb_husband h left join tb_child c on h.id=c.hid </select> <resultMap type=”Husband” id=”myhs2”> <id property=”id” column=”id”/> <result property=”name” column=”name”/> <result property=”age” column=”age”/> <!-- 嵌套集合--> <collection property=”childs” ofType=”Child”><id property=”id” column=”cid”/><result property=”name” column=”cname”/><result property=”infant” column=”infant”/></collection> <resultMap> collection實(shí)現(xiàn)一對(duì)多或多對(duì)多其中,ofType:為集合中泛型的數(shù)據(jù)類(lèi)型,也就是多的一方對(duì)應(yīng)的類(lèi)名。
3、collection和association嵌套使用
這個(gè)標(biāo)簽可以嵌套在一起使用,一般用來(lái)表達(dá)多對(duì)多的關(guān)系映射中:
<select id=”query” parameterType=”int” resultMap=”mp1”>select s.*,st.id stid,st.days,t.id teaid,t.name tname from tb_student s left join tb_studentrelation st on s.id=st.sid left join tb_teacher t on t.id=st.tid where s.id=#{id} </select> <!-- 多對(duì)多的中間表的關(guān)系--> <resultMap type=”Student” id=”mp1”> <id property=”id” column=”id”/> <result property=”name” column=”name”/> <!--和中間表存在一對(duì)多--> <collection property=”list” ofType=”StudentRelation”><id property=”id” column=”stid”/><result property=”days” column=”days”/><!-- 中間表和教師表存在多對(duì)一--><association property=”teacher” javaType=”Teacher”><id property=”id” column=”teaid”/><result property=”name” column=”tname”/></association></collection> <resultMap> collection和association嵌套使用?
轉(zhuǎn)載于:https://www.cnblogs.com/arrows/p/10382405.html
總結(jié)
以上是生活随笔為你收集整理的七、MyBatis教程之四多表关系的实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: PAT A1038
- 下一篇: Iterator 和 for...of