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>
  • 相关阅读:
    Java进阶——线程安全和非线程安全
    Java进阶——线程与多线程
    Java进阶——反射
    SpringBoot——SpringBoot框架介绍
    亲逢APP项目知识点
    诗韵APP项目技术点
    Spring框架——WebService
    Spring框架——ORM
    Spring框架——JDBC
    Spring框架——Spring响应
  • 原文地址:https://www.cnblogs.com/wyhluckdog/p/10156245.html
Copyright © 2011-2022 走看看