mybatis的#{}和${}的区别以及order by注入问题

一、问题

根据前端传过来的表格排序字段和排序方式,后端使用的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

原文地址:https://www.cnblogs.com/xieshuang/p/11017121.html