mybatis項目dao層中不少sql語句都會擁有某些相同的查詢條件,以<where><if test=""></if></where>的形式拼接在sql語句後,一個兩個的sql語句感受不到什麼,可是若是查詢語句特別多,可是查詢的條件老是相似的,那就能夠考慮把<where><if>這部分代碼抽取出來,封裝一下,而後須要條件搜索的sql語句直接引用就能夠了。sql
先來看下沒有抽取代碼以前的條件sql語句mybatis
第一條 <select id = "getUserEmailByProvinceAndOrderType" resultType="String"> select DISTINCT(wo_responsibility) from t_view_workorder <where> <if test="province != '全國' and province != null"> wo_province = #{province} </if> <if test="orderType != '所有' and orderType != null"> and wo_type = #{orderType} </if> <if test="email != ''"> and wo_responsibility = #{email} </if> </where> </select> 第二條 <select id = "getUndoneDelayOrderByProvinceAndOrderTypeAndUserEmail" resultType="com.chinamobile.sias.workorder.po.Workorder"> select * from t_view_workorder <where>
<if test="province != '全國' and province != null">
wo_province = #{province}
</if>
<if test="orderType != '所有' and orderType != null"> and wo_type = #{orderType} </if> <if test="email != ''"> and wo_responsibility = #{email} </if>
<if test="true"> and (wo_complete_time is null or wo_complete_time='') and (select curdate()) >= wo_regulations_time </if>
</where>
</select>
以上是兩條sql語句,能夠看出,兩個sql語句中有某些查詢條件是相同的spa
<if test="province != '全國' and province != null"> wo_province = #{province} </if> <if test="orderType != '所有' and orderType != null"> and wo_type = #{orderType} </if> <if test="email != ''"> and wo_responsibility = #{email} </if>
此時咱們就能夠對此段判斷條件進行提取。以下:code
<sql id="common_where_if"> <if test="province != '全國' and province != null"> wo_province = #{province} </if> <if test="orderType != '所有' and orderType != null"> and wo_type = #{orderType} </if> <if test="email != ''"> and wo_responsibility = #{email} </if> </sql>
此時把<where>標籤下相同的判斷條件提去了出來,id本身取,這裏定爲 common_where_if.blog
那麼如何使用這段代碼呢,以下:get
<include refid="common_where_if"/>
格式以下:it
<select id = "getUserEmailByProvinceAndOrderType" resultType="String"> select DISTINCT(wo_responsibility) from t_view_workorder <where> <include refid="common_where_if"/> </where> </select>
此時就在<where>標籤中引用了共用的判斷條件,再多的sql語句,再多的查詢條件,只須要一個<include>就能解決重複的代碼。io