ibatis的groupby的用处很多,比如把数据展示成树结构,目录结构等等。
ibatis的使用方法:
定义一个 resultMap,如下。
<resultMap id="SpreadGroupByPackageID" class="TChannelProduct" groupBy="productId,channelId "> <result property="productId" column="productId" /> <result property="channelId" column="channelId " /> <result property="channelProductlist" resultMap="cn.emag.product.domain.TChannelProduct.subchannelProduct " /> </resultMap>
还有一个一个resultMap,内容如下:
<resultMap id="subchannelProduct
" class="TChannelProduct">
<result property="id" column="id" />
<result property="spreadStartTime" column="spreadStartTime" />
<result property="spreadEndTime" column="spreadEndTime" />
<result property="productPageUrl" column="productPageUrl" />
<result property="productTargetUrl" column="productTargetUrl" />
<result property="isReferValid" column="isReferValid" />
<result property="businessMdId" column="businessMdId" />
<result property="bcidCode" column="bcidCode" />
<result property="productType" column="productType" />
<result property="balanceChannelId" column="balanceChannelId" />
<result property="businessMdName" column="businessMdName" />
<result property="businessMdCode" column="businessMdCode" />
<result property="productId" column="productId" />
<result property="channelId" column="channelId" />
<result property="spreadState" column="spreadState" />
<result property="channelName" column="channelName" />
<result property="channelCorpType" column="channelCorpType" />
<result property="companyCode" column="companyCode" />
<result property="companyName" column="companyName" />
</resultMap>
sql内容:
<select id="findSpreadGroupByPackageID" parameterClass="map" resultMap="SpreadGroupByPackageID"> select cp.id as id, cp.spread_start_time as spreadStartTime, cp.spread_end_time as spreadEndTime, cp.product_page_url as productPageUrl, cp.Product_Target_Url AS productTargetUrl, cp.is_refer_valid as isReferValid, cp.business_md_id as businessMdId, CP.Bcid_Code AS bcidCode, cp.product_type AS productType, cp.balance_channel_id AS balanceChannelId, bu.business_model_name as businessMdName, bu.business_model_code as businessMdCode, CP.PACKAGE_ID AS PRODUCTID , cp.channel_id as channelId , cp.SPREAD_STATE as spreadState, ci.channel_name as channelName, ci.CHANNEL_CORP_TYPE as channelCorpType, cc.company_code as companyCode, cc.company_name_cn as companyName from T_CHANNEL_PRODUCT_REF cp, t_channel_info ci, t_channel_corp cc, t_channel_busi_model bu where cp.channel_id = ci.id and ci.corp_id = cc.company_code and cp.business_md_id = bu.id and cp.Spread_State <![CDATA[<>]]> 2 </select>
实现的效果是,将同packageid同channelid的数据放到同一个list中去。
因为已packageid同channelid分组,所以,虽然 值需要获得list中数据,但是resultMap中叶需要将packageid和channelid加上去,否则没有任何效果。。。。,即上文中,红字部分 一定要注意,不要搞丢了。
事实上分组的实现不是在数据库中实现,而是查出所有数据后,在ibatis的代码中进行的实现,所以,如果需要进行分页查询。。。那就只能ibatis分组处理后,查出所需数据,然后对所有数据在代码中分组了。悲催。。。
看了 好几个帖子,搜索相关的实现,好多贴中groupby的resultMap中,都没有分组的那个数据的property,试了几次才发现,应该是现在这样的。