zoukankan      html  css  js  c++  java
  • 使用mybatis提供的各种标签方法实现动态拼接Sql。使用sql片段提取重复的标签内容

    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>
  • 相关阅读:
    解除对80端口的占用
    php排序算法
    Jquery异步请求数据实例
    C# winform 递归选中TreeView子节点
    C# WinFrom 编写正则表达式验证类
    c# winfrom 委托实现窗体相互传值
    [转]我的第一个WCF
    计算字符串中子串出现的次数
    JQuery中的html(),text(),val()区别
    Crystal Report制作使用
  • 原文地址:https://www.cnblogs.com/wyhluckdog/p/10156245.html
Copyright © 2011-2022 走看看