SQL语句的动态拼接(1)

[1]为什么使用动态拼接?

    在自我学习中只是针对数据做简单的增删改查操作,但是在实际的业务中,经常会根据不同的情况执行不同的SQL语句才可以。这个问题如何解决呢?

[2]解决方案

    SQL语句的动态拼接

[3]动态拼接标签

   常见的动态拼接标签:if   where  choose   set  trim  foreach  bind  sql  include

mapper接口

    List<Flower> selectMore(String name,String production);
    List<Flower> selectMore2(@Param("pa") String name);
    List<Flower> selectMore3(String name,String production);
    List<Flower> selectMore4(String name,String production);

 mapper.xml文件

<!--
        if  if(){}
            if(){}
            if(){}
    -->
    <select id="selectMore" resultType="flower">
        select  *  from  flower  WHERE  1=1
        <!--OGNL-->
        <if test="param1!=null and param1!=''">
            and  name =#{param1}
        </if>
        <if test="param2!=null  and  param2!=''">
          and  production=#{param2}
        </if>
    </select>
    <select id="selectMore2" resultType="flower">
        select  *  from  flower  WHERE  1=1
        <!--
          *如果按照条件查询的时候只有一个条件的时候接受参数必须起别名才可以
          -->
        <if test="aa!=null and aa!=''">
            and  name =#{aa}
        </if>
    </select>

    <!--
      where关键字 作用
        会自动的增加where关键字,并且会自动的去除第一个and
    -->
    <select id="selectMore3" resultType="flower">
        select  *  from  flower
        <where>
            <!--OGNL-->
            <if test="param1!=null and param1!=''">
                 AND  name =#{param1}
            </if>
            <if test="param2!=null  and  param2!=''">
                and  production=#{param2}
            </if>
        </where>
    </select>
      <!--
      choose
             if(){}
             else if(){}
             else if(){}
             else {}
      -->
    <select id="selectMore4" resultType="flower">
        SELECT   *  FROM  flower
        <where>
              <choose>
                  <when test="param1!=null and  param1!=''">
                     and name =#{param1}
                  </when>
                  <when test="param2!=null and  param2!=''">
                     and  production =#{param2}
                  </when>
                  <otherwise>
                       1=1
                  </otherwise>
              </choose>
        </where>
    </select>

 


版权声明:本文为Programer0原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。