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>
  • 相关阅读:
    在 Eclipse Workbench 之外使用 Eclipse GUI
    GB2312,GBK,Unicode
    木偶一之推荐系统
    Matlab:任意矩阵计算分布密度(海明距离的分布密度)
    live555在arm linux下的交叉编译,并下载的Arm板播放H264文件
    java设计模式之原型模式
    HDU 1102
    poj3661另一种做法(滚动数组)
    基于QT的小游戏细菌病毒战
    某代码查看器的保护突破
  • 原文地址:https://www.cnblogs.com/wyhluckdog/p/10156245.html
Copyright © 2011-2022 走看看