Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的,如下:


<select id="findUserByNameAndSex" parameterType="com.huida.po.User" resultType="com.huida.po.User">
<!-- select * from user where 1=1 and username like "%${username}%" and sex=#{sex} -->
  select * from user
  <!-- where标签有两个作用:
  1.替代where关键字
  2.会去掉第一个条件的and关键字,会自动加上1=1永真条件,也就是放当后面的条件为null时,执行永真条件
  -->
  <where>
    <if test="username!=null and username!=''">
      and username like "%${username}%"
    </if>
    <if test="sex!=null and sex!=''">
      and sex=#{sex}
    </if>
  </where>
</select>

 将where条件抽取出来,放到sql标签中:

<sql id="user_where">
        <!-- where标签有两个作用:
            1.替代where关键字
            2.会去掉第一个条件的and关键字,会自动加上1=1永真条件,也就是放当后面的条件为null时,执行永真条件
         -->
        <where>
            <if test="username!=null and username!=''">
                and username like "%${username}%"
            </if>
            <if test="sex!=null and sex!=''">
                and sex=#{sex}
            </if>
        </where>
    </sql>

使用的时候使用include引用:

<select id="findUserByNameAndSex" parameterType="com.huida.po.User" resultType="com.huida.po.User">
        <!-- select * from user where 1=1 and username like "%${username}%" and sex=#{sex} -->
        select * from user
        <!-- 将where抽取成一个sql片段,用的时候通过id进行引入 -->
        <include refid="user_where"></include>        
    </select>

 

posted on 2018-12-21 15:55  wyhluckydog  阅读(960)  评论(0编辑  收藏  举报