天天看點

java -- mybatis 模糊查詢不能直接用#{queryText} ,例如:#相當于占位符?,而?不能放在%%中。可以用${queryText},但是會容易sql注入攻擊推薦使用concat但是如果傳入特殊字元則又會有問題,例如傳入一個% 則會查詢所有。是以需要将%轉譯:在java中 \ 就代表轉譯 是以需要 \ \ 但是replaceAll内部使用正規表達式,是以又會将一個 \ 轉譯,是以需要 \\\\ 。同理 _ 類似 也需要轉譯 或者一些其他的特殊符。

mybatis中的模糊查詢

不能直接用#{queryText} ,例如:#相當于占位符?,而?不能放在%%中。

<select id="queryList" resultMap="BaseResultMap" >
    select id,loginacct,userpswd,username,email,createtime
    from t_user
    <where>
      <if test="queryText!=null"> loginacct LIKE "%#{queryText}%" </if>
    </where>
    limit #{startIndex},#{pagesize}
  </select>
           

可以用${queryText},但是會容易sql注入攻擊

<select id="queryList" resultMap="BaseResultMap" >
    select id,loginacct,userpswd,username,email,createtime
    from t_user
    <where>
      <if test="queryText!=null"> loginacct LIKE "%${queryText}%" </if>
    </where>
    limit #{startIndex},#{pagesize}
</select>
           

推薦使用concat

<select id="queryList" resultMap="BaseResultMap" >
    select id,loginacct,userpswd,username,email,createtime
    from t_user
    <where>
      <if test="queryText!=null"> loginacct LIKE concat("%",#{queryText},"%") </if>
    </where>
    limit #{startIndex},#{pagesize}
  </select>
           

但是如果傳入特殊字元則又會有問題,例如傳入一個% 則會查詢所有。

是以需要将%轉譯:

if (queryText.contains("%")){
    queryText = queryText.replaceAll("%","\\\\%");
}
           

在java中 \ 就代表轉譯 是以需要 \ \ 但是replaceAll内部使用正規表達式,是以又會将一個 \ 轉譯,是以需要 \\\\ 。

同理 _ 類似 也需要轉譯 或者一些其他的特殊符。