MyBatis中order by排序无效的问题

来源:互联网 发布:网络登山鞋 编辑:程序博客网 时间:2024/06/09 20:22

在使用MyBatis解析xml进行排序的时候,遇见排序无效的问题!

  • #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #{user_id},如果传入的值是111,那么解析成sql时的值为order by “111”, 如果传入的值是id,则解析成的sql为order by “id”。

  • $将传入的数据直接显示生成在sql中。如:order by ${user_id},如果传入的值是111,那么解析成sql时的值为order by 111, 如果传入的值是id,则解析成的sql为order by id。

  • 方式能够很大程度防止sql注入。

  • $方式无法防止Sql注入。

  • $方式一般用于传入数据库对象,例如传入表名。

  • 一般能用#的就别用$。

所以order by 之后要使用$而非#。

附解决代码段:

其中orderByField就是传入进行排序的参数值!

<choose>  <when test="orderByField != null and orderByField !=''">    <choose><when test="isAsc == true">      order by ${orderByField} ASC  </when>  <otherwise>    order by ${orderByField} DESC  </otherwise></choose>  </when><otherwise>  order by id DESC</otherwise></choose>