MyBatis中order by排序无效的问题

在使用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>

猜你喜欢

转载自blog.csdn.net/it_dx/article/details/78866772