1. 程式人生 > >mybatis 高階結果對映關聯的巢狀查詢、一對多查詢

mybatis 高階結果對映關聯的巢狀查詢、一對多查詢

這是mybatis的官方例子,基本上看一遍就會了,一定要先去看官方例子,這裡介紹的不詳細

http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#select

我自己用的聯表查詢

實體類

public class MemberSaleRecordsResult {
	
    private String code;
    
    private String name;
    
    private Integer id;
    // 銷售商品集合
	private List<SaleGoods> detailList;
}

resulrMap定義

collection 的property屬性是resultMap對應實體類MemberSaleRecordsResult中的detailList屬性名。

collection 的ofType屬性是集合對應的實體類,column是表的主鍵id,官方說加上可以提高效率。

<resultMap id="BaseResultMap" type="MemberSaleRecordsResult">
    <!-- 會員 -->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="code" jdbcType="VARCHAR" property="code" />
    <!-- 集合 (detailList是實體類中的一個集合屬性名) -->
    <collection property="detailList" ofType="SaleGoods" column="id" >
<!-- 這裡的column對應的是下面查詢的別名,而不是表字段名;為了防止欄位衝突,銷售表字段統一加字首‘sale_’ ,以銷售表主鍵id為例,把銷售id重新命名為sale_id -->
		<id column="sale_id" jdbcType="INTEGER" property="id"/>
		<result column="sale_create_time" jdbcType="TIMESTEMP" property="createTile"/>
		<result column="sale_goods_name" jdbcType="VARCHAR" property="goodsName"/>
	</collection>
  </resultMap>

sql語句

<select id="findMemberSaleRecords" parameterType="MemberSaleRecordsQuery" resultMap="BaseResultMap">
    select 
    bm.id, bm.name, bm.code, 
    det.id as sale_id, det.create_time as sale_create_time, det.goods_name as sale_goods_name
    from (select id,name,company_code 
    		from base_member 
    		<where>
		    	<if test="searchKey != null and searchKey != ''">
		    		 AND (
				        code LIKE concat('%',#{searchKey},'%')
				        or name LIKE concat('%',#{searchKey},'%')
				        )
		    	</if>
		    </where>
    		limit #{start},#{pageSize}
    	) bm 
    left join sale_detail det on bm.id = det.member_id 
  </select>

        可能會有疑惑為什麼不能寫在最後呢,應為查詢出來的資料是一對多的,舉個例子,看我下面limit 0,10查出來的資料,因為會員是主表所以會員資訊重複了,查出來的資料經過mybatis處理,實體類MemberSaleRecordsResult中的detailList返回的listSize只有3。這就是為什麼分頁要加在主表裡了;還有就是為什麼要加分頁,要想想成千上萬的會員和銷售記錄聯表,資料庫會炸掉的。