使用Mybatis分頁插件PageHelper時的分頁問題mybatis
1對1查詢,分頁正常spa
1對多查詢,如使用左右鏈接查詢則會致使結果的總記錄條數,子記錄條數會疊加到主記錄條數,致使數據不對稱。插件
總結:使用mybatis時,在一對多的查詢而且須要分頁的時候須要使用子查詢形式。code
1) 主記錄的resultMap
<resultMap id="artWorkMap" type="Artwork"> <id column="id" jdbcType="VARCHAR" property="id"></id> <result column="commited" jdbcType="VARCHAR" property="commited"></result> <association property="user"> <id column="u_id" jdbcType="VARCHAR" property="id"></id> <result column="u_username" jdbcType="VARCHAR" property="username"></result> </association> <association property="template" resultMap="templateRigMap"> </association> <collection property="materialCompositions" ofType="MaterialComposition"
select="selectMaterialCompositions" ### 關聯的子查詢
column="id"> ### 傳主記錄的列名的參數值 </collection> </resultMap>
2) 子記錄的ResultMap,依次爲 "1對1" 的與 "1對多" 的
<resultMap id="templateRigMap" type="Template">
<id column="bt_id" jdbcType="VARCHAR" property="id"></id>
<result column="bt_template_name" jdbcType="VARCHAR" property="templateName"></result>
<result column="bt_deleted" jdbcType="BIT" property="deleted"></result>
<result column="bt_create_date" jdbcType="TIMESTAMP" property="createDate"></result>
</resultMap>
<resultMap id="materialCompositionsRigMap" type="MaterialComposition">
<id column="bmc_id" jdbcType="VARCHAR" property="id"></id>
<result column="bmc_artwork_id" jdbcType="VARCHAR" property="artworkId"></result>
</resultMap>
3)主記錄查詢 (把一對一的查詢放在一塊兒,一對多的數據另寫一條查詢)
<select id="selectAllOrInCompany" resultMap="artWorkMap">
SELECT
ba.*
,su.id "u_id"
,su.username "u_username"
,bc.id
,bc.company_no
,bc.update_date "c_update_date"
,bb.id "bb_id"
,bb.update_date "bb_update_date"
,bt.id "bt_id"
,bt.update_date "bt_update_date"
from biz_artwork ba
left join sys_user su on su.id = ba.user_id
left join biz_company bc on bc.id = su.company_id
left join base_brand bb on ba.brand_id = bb.id
left join base_template bt on ba.template_id = bt.id
where ba.deleted = 0
<choose>
<when test="companyNo !=null and companyNo != ''">
and ba.artwork_no like concat('', #{companyNo}, '%')
</when>
<otherwise>
and ba.commited = 1
</otherwise>
</choose>
<if test="keywords !=null and keywords.length() > 0">
and (
ba.artwork_no like concat('%', #{keywords}, '%')
or su.username like concat('%', #{keywords}, '%')
or bc.company_name like concat('%', #{keywords}, '%')
)</if>
order by ba.update_date desc
</select>
4)子記錄查詢
<select id="selectMaterialCompositions" resultMap="materialCompositionsRigMap">
select
bmc.id "bmc_id"
,bmc.create_date "bmc_create_date"
,bmc.update_date "bmc_update_date"
from biz_material_composition bmc
where bmc.artwork_id = #{id} ### 接收主記錄的列名的參數值
</select>