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