mybatis項目dao層中很多sql語句都會擁有某些相同的查詢條件,以<where><if test=""></if></where>的形式拼接在sql語句后,一個兩個的sql語句感覺不到什么,但是如果查詢語句特別多,但是查詢的條件總是類似的,那就可以考慮把<where><if>這部分代碼抽取出來,封裝一下,然后需要條件搜索的sql語句直接引用就可以了。
先來看下沒有抽取代碼之前的條件sql語句
第一條 <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語句中有某些查詢條件是相同的
<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 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.
那么如何使用這段代碼呢,如下:
<include refid="common_where_if"/>
格式如下:
<select id = "getUserEmailByProvinceAndOrderType" resultType="String"> select DISTINCT(wo_responsibility) from t_view_workorder <where> <include refid="common_where_if"/> </where> </select>
此時就在<where>標簽中引用了共用的判斷條件,再多的sql語句,再多的查詢條件,只需要一個<include>就能解決重復的代碼。