/ #{} 和 ${} 详解
动态 sql 是 mybatis 的主要特性之一,在 mapper 中定义的参数传到 xml 中之后,在查询之前 mybatis 会对其进行动态解析。
mybatis 为我们提供了两种支持动态 sql 的语法:#{} 以及 ${} 。
如: #{} : 根据参数的类型进行处理,比如传入String类型,则会为参数加上双引号。#{} 传参在进行SQL预编译时,会把参数部分用一个占位符 ? 代替,这样可以防止 SQL注入。
如: ${} : 将参数取出不做任何处理,直接放入语句中,就是简单的字符串替换,并且该参数会参加SQL的预编译,需要手动过滤参数防止 SQL注入。
因此 mybatis 中优先使用 #{};当需要动态传入 表名或列名 时,再考虑使用 ${} 。
其中 ${} 比较特殊, 他的应用场景是 需要动态传入 表名或列名时使用。下面举例:
这段代码可以查出数据,但是根据业务来看是有问题的,他不能进行排序,因为 #{birthday} 解析出来后是一个 带着双引号的字符串,mysql找不到这样的列名,因此不能进行排序。
<select id="getList" resultType="com.ccyang.UserDao">
select
u.user_id, u.user_name, u.user_type, u.age, u.sex, u.birthday
from
user u
<where>
u.user_age in <foreach collection="ages" item="item" index="index" open="(" separator="," close=")">#{item}</foreach>
and u.sex == "男"
<if test="u.user_name != null and u.user_name != ''"> AND u.user_name like CONCAT(CONCAT('%', #{userName}), '%')</if>
<if test="order_by!= null and order_by != ''"> order by #{order_by} DESC</if>
</where>
</select>
正确的写法应该是使用 ${order_by},这样解析后就是一个列名,然后才能对数据进行排序,已达到业务需求。
<!-- 条件查询 -->
<select id="getList" resultType="com.ccyang.UserDao">
select
u.user_id, u.user_name, u.user_type, u.age, u.sex, u.birthday
from
user u
<where>
u.user_age in <foreach collection="ages" item="item" index="index" open="(" separator="," close=")">#{item}</foreach>
and u.sex == "男"
<if test="u.user_name != null and u.user_name != ''"> AND u.user_name like CONCAT(CONCAT('%', #{userName}), '%')</if>
<if test="order_by!= null and order_by != ''"> order by ${order_by} DESC</if>
</where>
</select>
网友评论