zoukankan      html  css  js  c++  java
  • mybatis审查要点

    1.where条件遗漏情况

    <select id="findActiveBlogLike" resultType="Blog">
      SELECT * FROM BLOG 
      <where> 
        <if test="state != null">
             state = #{state}
        </if> 
        <if test="title != null">
            AND title like #{title}
        </if>
      </where>
    </select>
    
     遗漏了state != null &&title != null的情况,导致全表查询,甚至会导致内存泄露。
    可以采用下面的方法将别的情况写在otherwise中,或者在otherwise中写 1=2。
    <choose>
            <when test="processStatus != null &amp;&amp; processStatus != '' &amp;&amp; processStatus != '-110'">
               and process_status = #{processStatus,jdbcType=VARCHAR} 
            </when>
            <otherwise>
                and process_status != 1
            </otherwise>
        </choose>
    

    2.对特殊符号的处理

    下面的这些符号大于号、小于号、不等号、&、单引号和双引号在Mybatis的xml文件中不能有效识别,如果直接这样写是有问题,会导致文件编译出错。
     > < <>  & ' " 
    
    两种办法来解决
    第一种是把这些符号进行转义:
     &gt;          > 
     &lt;           < 
     &lt;&gt;   <> 
     &amp;      &
     &apos;      ' 
     &quot;      " 
    左边的就是转义的字符表示,用这些就能走在xml文件中正确使用步骤一种不能正常使用的特殊符号了。
    
    另外一种解决的方式:
    <![CDATA[ >= ]]>
    来表示特殊符号,可以把整个sql语句写在<![CDATA[  ]]>中,这样这些特殊符号就可以正常编译了
    

    3.if判断注意点

    注意:下面这种写法只适用于 id 类型为字符串.
      <if test="id != null and id != '' ">
      id = #{id}
      </if>
    如果id类型为int 当id=0时 这个判断不会进入.

    4.编写mybatis的映射语句时,尽量采用“#{xxx}”这样的格式来避免sql注入,不要使用“${xxx}”

    1.采用“#{xxx}”这样的格式的sql会采用预编译的形式,用?来占位
    
    <select id="getBlogById" resultType="Blog"parameterType=”int”>
    select id,title,author,content
    from blog where id=#{id}
    </select>
    
    最后会编译成
    selectid,title,author,content from blog where id = ?
    这样在执行的时候 ,再将具体的参数注入进去,防止sql注入。
    
    2.采用“${xxx}”这样的格式的sql,在编译阶段就回将参数带入
    <select id="orderBlog" resultType="Blog"parameterType=”map”>
    select id,title,author,content
    from blog order by ${orderParam}
    </select>
    最后编译形成的sql为
    select id,title,author,content fromblog order by id
    这样就可能会sql注入。
    
    因此在必须需要使用 ${xxx}的形式的时候(需要用此来动态创建表明和列名的时候),在代码层面来做手工过滤(不能有空格和and or等关键词,只能由26个字母组成等)。
  • 相关阅读:
    动态规划(DP计数):HDU 5117 Fluorescent
    动态规划(DP计数):HDU 5116 Everlasting L
    动态规划(区间DP):HDU 5115 Dire Wolf
    数学(扩展欧几里得算法):HDU 5114 Collision
    二叉树面试题
    linux eval命令
    关于Shell中命令替换$(...)与后置引用`...`的不同
    linux set,env和export
    linux crontab 命令
    排序
  • 原文地址:https://www.cnblogs.com/shibazijiang/p/5568715.html
Copyright © 2011-2022 走看看