原文鏈接:http://blog.csdn.net/laiwanwanyihao/article/details/72943421,是本博主寫的,
附源碼,免費下載
前言
好久沒用過mybatis了,現在復習一下,順帶着整理一下東西,
本人maven用的不好,架構參照來源http://www.cnblogs.com/GarfieldEr007/p/5746263.html,
本片文章例子為簡單的小例子,參考的文章也是介紹mybatis,不過我沒看,我就下了maven架構就開始搞自個的例子了,因為原博主的文章寫得太長了,懶得看了
maven架構
maven構架springMvc+mybatis這里我就不一一展示了,想必各位都知道,不清楚的看源碼就行了,
數據庫
數據庫很簡單 三個表 A AB B 其中AB為中間表,A 與 B 為多對多關系,,,今天就整理下A與B多對多和A與AB一對多的兩種關聯映射處理,(注意數據庫中表字段不要重名,比如A表主鍵與B表主鍵不要重名,不然查出來結果會不全,陷這個坑好久才明白過來)
多對多
- <!-- 多對多 -->
- <resultMap id="BaseResultMap2" type="cn.test.model.A">
- <id column="aid" property="aid" jdbcType="INTEGER" />
- <result column="a_name" property="aname" jdbcType="VARCHAR" />
- <collection property="bLists" ofType="cn.test.model.B">
- <id property="bid" column="bid" />
- <result property="bname" column="b_name" />
- </collection>
- </resultMap>
- <select id="selectAByIdUnionB" resultMap="BaseResultMap2"
- parameterType="java.lang.Integer">
- select
- *
- from a inner join a_b on a.aid = a_b.a_id inner
- join b on a_b.b_id = b.bid where a.aid=#{id jdbcType="INTEGER"}
- </select>
- //多對多
- @org.junit.Test
- public void seectAByIdUnionB() {
- for(A a:aService.selectAByIdUnionB(1)){
- System.out.print(a.getAname()+">>>>>>>");
- for(B b :a.getbLists() ){
- System.out.print(b.getBname());
- }
- System.out.println("\n");
- }
- }
結果
一對多
- <!-- 一對多 -->
- <resultMap type="cn.test.model.A" id="OneToManay">
- <id column="aid" property="aid" jdbcType="INTEGER" />
- <result column="a_name" property="aname" jdbcType="VARCHAR" />
- <collection property="abLists" ofType="cn.test.model.AB">
- <id property="id" column="id" />
- <result property="a" column="a_id" />
- <result property="b" column="b_id" />
- </collection>
- </resultMap>
- <select id="selectAtoAB" resultMap="OneToManay" parameterType="INTEGER">
- select * from a inner join a_b on a.aid=a_b.a_id where a.aid=#{id jdbcType="INTEGER"}
- </select>
測試
- //一對多
- @org.junit.Test
- public void onetomany(){
- for(A a :aService.selectAtoAB(1)){
- System.out.print(a.getAname()+">>>>>>>");
- for (AB ab : a.getAbLists()) {
- System.out.print(ab.getId());
- //System.out.print(ab.getA());
- //System.out.print(ab.getB());
- }
- System.out.println("\n");
- }
- }
結果
好了 希望給各位需要的同志們有所幫助,
源碼下載地址:http://download.csdn.NET/detail/laiwanwanyihao/9865160