zoukankan      html  css  js  c++  java
  • mybatis动态sql详情

    动态SQL是mybatis的强大特性之一,MyBatis的动态SQL是基于OGNL表达式来完成的,它可以帮助我们方便的在SQL语句中实现某些逻辑。
    MyBatis中用于实现动态SQL的元素主要有:

    元素 说明
    <if> 判断语句,用于单分支判断
    <choose>(<when>、<otherwise>) 相当于java的switch···case···default语句,用于多分支判断
    <where>、<trim>、<set> 辅助元素,用于处理一些SQL拼装、特殊字符问题
    <foreach> 循环语句,常用于in语句等列举条件中
    <bind> 从ognl表达式中创建一个变量,并将其绑定到上下文,常用于模糊查询的sql中

    一、if元素

    在mybatis中if是最常用的判断语句,用来进行一些简单的判断,然后进行动态sql的拼接。在使用==的时候需要使用toString()方法,这样更加稳定一些。如下例子所示:

    <select id="dynamicIfTest" parameterType="Blog" resultType="Blog">  
        select * from t_blog where 1 = 1  
        <if test="title != null">    <!-- test属性用于条件判断语句中,用于判断真假 -->
            and title = #{title}  
        </if>  
        <if test="content != null">  
            and content = #{content}  
        </if>  
        <if test="index=='1'.toString()">  
            and index= #{index}  
        </if>  
        <if test="owner != null">  
            and owner = #{owner}  
        </if>  
    </select>  
    

    二、choose(when,otherwise)元素

    这个类似于switch多分支语句。

    <select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">  
        select * from t_blog where 1 = 1   
        <choose>  
            <when test="title != null">  
                and title = #{title}  
            </when>  
            <when test="content != null">  
                and content = #{content}  
            </when>
            <when test="job !=null and jobs !=''"> 
                and jobs like concat('%',#{jobs},'%')    <!--concat('%',#{jobs},'%')用于拼接操作-->
            </when> 
            <otherwise>  
                and owner = "owner1"  
            </otherwise>  
        </choose>  
    </select>  
    

    三、where、trim元素

    1、<where>元素
    以上的例子中sql语句后面都加上了where 1 = 1条件,为什么要加这个条件呢,如果不加这个条件,那么拼接出来的sql会是这样的:
    select * from t_customer wher and username like concat('%',#{username},'%'),仔细观察会发现where后面直接跟的and,这样运行时肯定会报错,而加入了条件1=1后,既保证了where后面的条件成立,又避免了where后面第一个词是and或者or之类的关键词。

    如果想要不加这个条件也能实现的话,就需要使用<where>这个元素。它的作用主要是简化SQL语句中where中的条件判断的。

    <select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">  
        select * from t_blog   
        <where>  
            <if test="title != null">  
                and title = #{title}  
            </if>  
            <if test="content != null">  
                and content = #{content}  
            </if>  
            <if test="owner != null">  
                and owner = #{owner}  
            </if>  
        </where>  
    </select>  
    

    在以上配置中使用<where>元素对“where 1=1”条件进行了替换,<where>元素会自动判断组合条件下拼装的SQL语句,只有<where>元素内的条件成立时,才会在拼接SQL中加上where关键字,否则不会添加;即使where之后有多余的and或or关键字,<where>元素也会自动将它们去除。

    2、<trim>元素

    trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;使用trim元素不会出现语法错误,正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能,示例代码如下:

    <select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">  
        select * from t_blog   
        <trim prefix="where" prefixOverrides="and |or">  
            <if test="title != null">  
                title = #{title}  
            </if>  
            <if test="content != null">  
                and content = #{content}  
            </if>  
            <if test="owner != null">  
                or owner = #{owner}  
            </if>  
        </trim>  
    </select> 
    

    四、set元素

    set元素主要用于更新操作,其主要作用是在动态包含的SQL语句前输出一个set关键字,并将SQL语句中最后一个多余的逗号去除。有了set元素我们就可以动态的更新那些修改了的字段。下面是一段示例代码:

    <update id="dynamicSetTest" parameterType="Blog">  
        update t_blog  
        <set>  
            <if test="title != null">  
                title = #{title},  
            </if>  
            <if test="content != null">  
                content = #{content},  
            </if>  
            <if test="owner != null">  
                owner = #{owner}  
            </if>  
        </set>  
        where id = #{id}  
    </update>  
    

    需要注意的是:set元素中的内容不能都为空,如果都为空会出现语法错误。所以在进行更新的时候必须确保字段不能都为空。
    还有一种写法如下所示:

    <update id="updateOne"  parameterType="com.inspur.search.data.EntityRelation">
     UPDATE ENTITY_RELATION
     <trim prefix="set" suffixOverrides=",">
      <if test="srcId!=null">SRC_ID=#{srcId},</if>
      <if test="srcType!=null">SRC_TYPE=#{srcType},</if>
      <if test="destId!=null">DEST_ID=#{destId},</if>
      <if test="destType!=null">DEST_TYPE=#{destType},</if>
      <if test="relType!=null">REL_TYPE=#{relType},</if>
      <if test="status!=null">STATUS=#{status},</if>
      <if test="snId!=null">SN_ID=#{snId},</if>
     </trim>
     WHERE id=#{id}
    </update>
    

    参见博文: https://www.cnblogs.com/myitroad/p/5516963.html

    五、foreach元素

    <foreach>元素用于进行迭代遍历操作,因为有时候查询的数据不止一条。这是mybatis用于数组和集合的遍历方式。这个元素通常在构建in条件语句时使用。

    foreach元素的属性主要有item,index,collection,open,separator,close。
    item表示集合中每一个元素进行迭代时的别名;
    index指定一个名字,用于表示在迭代过程中每次迭代到的位置即下标;
    open表示该语句以什么开始;
    separator表示在每次进行迭代之间以什么符号作为分隔符;
    close表示以什么结束。
    在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的。
    但是在不同情况下,该属性的值是不一样的,主要有一下4种情况:

    1、如果传入的是单参数且参数类型是一个List的时候,collection属性值为list;

    2、如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array;

    3、如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key。

    4、如果传入的是POJO包装类的时候,collection属性值就为该包装类中需要进行遍历的数组或集合的属性名。

    <select id="dynamicForeachTest" resultType="Blog">  
        select * from t_blog where id in  
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
            #{item}  
        </foreach>  
    </select>  
    

    这个是单参数的时候,为list类型,它的mapper代码文件:

    public List<Blog> dynamicForeachTest(List<Integer> ids);  
    

    单参数array数组的类型时:

    <select id="dynamicForeach2Test" resultType="Blog">  
        select * from t_blog where id in  
        <foreach collection="array" index="index" item="item" open="(" separator="," close=")">  
            #{item}  
        </foreach>  
    </select>
    

    对应的mapper 代码文件:

    public List<Blog> dynamicForeach2Test(int[] ids); 
    

    自己把参数封装成Map的类型

    <select id="dynamicForeach3Test" resultType="Blog">  
        select * from t_blog where title like "%"#{title}"%" and id in  
        <foreach collection="ids" index="index" item="item" open="(" separator="," close=")"> 
            #{item}  ---ids为map中的键,而item就是键对应的值
        </foreach>  
    </select>
    

    对应的mapper代码文件:

    public List<Blog> dynamicForeach3Test(Map<String, Object> params); 
    

    测试:

    @Test  
    public void dynamicForeach3Test() {  
        SqlSession session = Util.getSqlSessionFactory().openSession();  
        BlogMapper blogMapper = session.getMapper(BlogMapper.class);  
        final List<Integer> ids = new ArrayList<Integer>();  
        ids.add(1);  
        ids.add(2);  
        ids.add(3);  
        ids.add(6);  
        ids.add(7);  
        ids.add(9);  
        Map<String, Object> params = new HashMap<String, Object>();  
        params.put("ids", ids);  
        params.put("title", "中国");  
        List<Blog> blogs = blogMapper.dynamicForeach3Test(params);  
        for (Blog blog : blogs)  
            System.out.println(blog);  
        session.close();  
    }  
    

    六、bind元素

    在进行模糊查询时,使用${}进行字符串拼接是无法防止sql注入的,但是如果使用concat()函数进行连接,但是只对mysql有效而Oracle需要使用||,而bind元素可以实现跨越数据库使用。它的功能是在当前OGNL上下文中创建一个变量并绑定一个值。

    <select id="fuzzyQuery" resultType="Blog" parameterType="java.lang.String">    
          <!-- bind标签用于创建新的变量 _parameter为传入的参数-->  
          <bind name="titleLike" value="'%'+_parameter+'%'"/>  
          select * from t_blog where title like #{titleLike}    
    </select> 
    
  • 相关阅读:
    【贪心】CodeForces-545C:Woodcutters
    【贪心】雷达问题
    【贪心】poj1328:雷达设置
    【最短路】HDU2680:Choose the best route
    2018年第四阶段组队训练赛第九场
    第四阶段组队训练赛第八场
    2018年第四阶段组队训练赛第七场
    第四阶段组队训练赛第六场( 题源:UKIEPC2017)
    Coins I
    2018年第四阶段组队训练赛第五场
  • 原文地址:https://www.cnblogs.com/jasonboren/p/11394721.html
Copyright © 2011-2022 走看看