一、問題
根據前端傳過來的表格排序字段和排序方式,后端使用的mybaits
select XXXX from table order by #{column} #{desc}
如上面的形式發現排序沒有生效,查看打印的日志發現實際執行的sql為,排序沒有生效
select XXXXX from table order by "column" "desc"
二、原因分析
主要還是對mybatis傳參形式不了解,官方介紹如下:
By default, using the #{} syntax will cause MyBatis to generate PreparedStatement properties and set the values safely against the PreparedStatement parameters (e.g. ?). While this is safer, faster and almost always preferred, sometimes you just want to directly inject an unmodified string into the SQL Statement. For example, for ORDER BY, you might use something like this:
@Select("select * from user where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);
從官方文檔中可以看出#{}
相當於jdbc中的preparedstatement,進行了預編譯,而${}
直接是字符串本身,是有意設計成這樣,方便拼接成動態sql,但是這樣也帶來缺點,可能存在注入問題。
參考閱讀:http://www.mybatis.org/mybatis-3/sqlmap-xml.html#Parameters