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。这就是为什么分页要加在主表里了;还有就是为什么要加分页,要想想成千上万的会员和销售记录联表,数据库会炸掉的。

猜你喜欢

转载自blog.csdn.net/DavidSoCool/article/details/84140959
今日推荐