Mybatis 的分頁條件查詢語句編寫


剛來到一家新公司, 翻看項目代碼, 發現一位同事寫的查詢邏輯很好, 不用插件, 一個語句完成了分頁條件查詢.

而我之前一般都是在業務層對參數進行判斷, 如果有條件,就調用條件查詢的方法, 如果沒有條件, 就調用查詢所有的方法, 代碼冗余較多

貼下代碼:

 

1, 首先定義resultMap:

  

<resultMap id="xxxModel" type="com.aaa.XxxModel">
<id column="id" javaType="java.lang.Long" jdbcType="BIGINT" property="id" />
<result column="ip" javaType="java.lang.String" jdbcType="VARCHAR" property="ip" />
<result column="port" javaType="java.lang.Integer" jdbcType="INTEGER" property="port" />
<result column="userName" javaType="java.lang.String" jdbcType="VARCHAR" property="userName" />
<result column="password" javaType="java.lang.String" jdbcType="VARCHAR" property="password" />
<result column="lineNum" javaType="java.lang.Integer" jdbcType="INTEGER" property="lineNum" />
<result column="isInternation" javaType="java.lang.Integer" jdbcType="INTEGER" property="isInternation" />
<result column="createDate" javaType="java.lang.String" jdbcType="VARCHAR" property="createDate" />
<result column="updateDate" javaType="java.lang.String" jdbcType="VARCHAR" property="updateDate" />
</resultMap>


2, 定義sql片段, 方便閱讀:
//條件和分頁參數的封裝, 利用動態sql, 特別是模糊查詢的%拼接, 很贊:
<sql id="pageListCount">
from anti_http_proxy a
<if test="groupId != null and groupId !=''">
LEFT JOIN anti_proxy_group b on a.`host` = b.`host`
LEFT JOIN anti_group_server c on b.group_id = c.group_id
</if>
where 1=1
<if test="ip != null and ip !=''">
and a.`host` like CONCAT('%','${ip}','%')
</if>
<if test="groupId != null and groupId !=''">
and c.id = #{groupId}
</if>
ORDER BY a.gmt_modified desc
<if test="(pageNumber != null and pageNumber != '' or pageNumber == 0) and pageSize != null and pageSize != ''">
limit #{pageNumber}, #{pageSize}
</if>
</sql>


<sql id="resultCol">
a.id
,a.`host` as ip
,a.`port`
,a.username as userName
,a.`password`
,a.band as lineNum
,a.international as isInternation
,DATE_FORMAT(a.gmt_create,'%Y-%m-%d %H:%i:%s') as createDate
,DATE_FORMAT(a.gmt_modified,'%Y-%m-%d %H:%i:%s') as updateDate
</sql>
3, 完成查詢方法
<select id="selectAllByPage" resultMap="xxxModel">
select
<include refid="resultCol" />
<include refid="pageListCount" />
</select>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM