mybatis 中 #{} 和 ${} 的区别及应用场景

一、#{} 和 ${} 详解

动态 sql 是 mybatis 的主要特性之一,在 mapper 中定义的参数传到 xml 中之后,在查询之前 mybatis 会对其进行动态解析。mybatis 为我们提供了两种支持动态 sql 的语法:#{} 以及 ${} 。 

  • #{} : 根据参数的类型进行处理,比如传入String类型,则会为参数加上双引号。#{} 传参在进行SQL预编译时,会把参数部分用一个占位符 ? 代替,这样可以防止 SQL注入。
  • ${} : 将参数取出不做任何处理,直接放入语句中,就是简单的字符串替换,并且该参数会参加SQL的预编译,需要手动过滤参数防止 SQL注入。
  • 因此 mybatis 中优先使用 #{};当需要动态传入 表名或列名时,再考虑使用 ${} 。

  • 其中 ${} 比较特殊, 他的应用场景是 需要动态传入 表名或列名时使用。下面举例

二、应用场景

  1. 看下面的SQL语句, 功能是查出年龄使用 IN 运算符,姓名采用模糊查询的一些男生,按照出生时间降序排列。但是下面这代码是达不到需求的,读者可以自己先找找问题。
<!-- 条件查询 -->
    <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>

上面这段代码可以查出数据,但是根据业务来看是有问题的,他不能进行排序,因为 #{birthday} 解析出来后是一个 带着双引号的字符串,mysql找不到这样的列名,因此不能进行排序。
2. 正确的写法应该是使用 ${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>

使用 ${} 动态传入表名或列名就可以达到需求,但是要小心SQL注入问题。

猜你喜欢

转载自blog.csdn.net/annotation_yang/article/details/81485696