1. 程式人生 > >MyBatis動態排序問題

MyBatis動態排序問題

在使用MyBatis時加入來按指定欄位進行排序

  ORDER BY
        <choose>
        <when test="sort!=null">
                #{sort,jdbcType=VARCHAR}
            <if test="order!=null">
                #{order,jdbcType=VARCHAR}
            </if>
        </when>
        <otherwise>
            id
asc , create_time asc </otherwise> </choose>

執行後,加入的排序無效
原因是: #{order,jdbcType=VARCHAR},MyBatis會自動將排序欄位當成一個字串,等同於order by ‘create_time’ ‘desc’,可以通過執行,但無效,與order by create_time desc結果不同
解決方法: 使用order,Mybatis,{order},因此修改如下

  ORDER BY
        <choose
>
<when test="sort!=null"> ${sort} <if test="order!=null"> ${order} </if> </when> <otherwise> id asc , create_time asc </otherwise> </choose>

注:
#能很大程度的防止SQL注入
$

無法防止Sql注入
$用於傳入資料庫物件
<![CDATA[]]>,在該符號內的語句,不會被當成字串來處理,而是直接當成sql語句,比如要執行一個儲存過程。在mapper檔案中寫sql語句時,遇到特殊字元時,如:< > 等,建議使用