水下功夫做透,水上才能顺风顺水。

mybatis中#{} 和 ${}的区别


#{} 和 ${} 的区别

(1)#{} 为参数占位符 ?,即sql 预编译,动态解析 -> 预编译 -> 执行
${} 为字符串替换,即 sql 拼接,动态解析 -> 编译 -> 执行

(2)#{} 的变量替换是在DBMS 中,变量替换后,#{} 对应的变量自动加上单引号 ,#{} 能防止sql 注入
${} 的变量替换是在 DBMS 外,变量替换后,${} 对应的变量不会加上单引号,${} 不能防止sql 注入

#{} 和 ${} 在使用中的技巧和建议

(1)不论是单个参数,还是多个参数,一律都建议使用注解@Param("")
(2)能用 #{} 的地方就用 #{},不用或少用 ${}
(3)表名作参数时,必须用 ${}。如:select * from ${tableName}
(4)order by 时,必须用 ${}。如:select * from t_user order by ${columnName}
(5)使用 ${} 时,要注意何时加或不加单引号,即 ${} 和 '${}'
         假设传入参数为 1
        #{}:select * from t_user where uid=#{uid}
        ${}:select * from t_user where uid='${uid}'

 

resultType 字段名和变量名直接映射。

resultMap 字段名和变量名通过Map映射。

<select id="queryVirtualClassInfoByStudentId" resultType="com.lingoace.pub.classroom.domain.response.ClassNameResp">
select cci.class_name as className,
cci.class_name_zh as classNameZh",
cci.id as id
from smallclass_class_info cci
</select>

 

  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from bigclass_virtualclass_member
    where id = #{id,jdbcType=INTEGER}
  </select>

 

posted @ 2020-05-25 08:53  北方寒士  阅读(305)  评论(0编辑  收藏  举报