博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mybatis中#{}和${}的区别
阅读量:7102 次
发布时间:2019-06-28

本文共 1308 字,大约阅读时间需要 4 分钟。

mybatis本身的说明:

String SubstitutionBy 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 a string unmodified into the SQL Statement. For example, for ORDER BY, you might use something like this:ORDER BY ${columnName}Here MyBatis won't modify or escape the string.NOTE It's not safe to accept input from a user and supply it to a statement unmodified in this way. This leads to potential SQL Injection attacks and therefore you should either disallow user input in these fields, or always perform your own escapes and checks.

从上文可以看出:

1. 使用#{}格式的语法在mybatis中使用Preparement语句来安全的设置值,执行sql类似下面的:

PreparedStatement ps = conn.prepareStatement(sql);ps.setInt(1,id);

这样做的好处是:更安全,更迅速,通常也是首选做法。

2. 不过有时你只是想直接在 SQL 语句中插入一个不改变的字符串。比如,像 ORDER BY,你可以这样来使用:

ORDER BY ${
columnName}

此时MyBatis 不会修改或转义字符串。

这种方式类似于:

Statement st = conn.createStatement();             ResultSet rs = st.executeQuery(sql);

这种方式的缺点是: 以这种方式接受从用户输出的内容并提供给语句中不变的字符串是不安全的,会导致潜在的 SQL 注入攻击,因此要么不允许用户输入这些字段,要么自行转义并检验。

 

 

参考文献:

【1】http://mybatis.github.io/mybatis-3/sqlmap-xml.html

【2】https://mybatis.github.io/mybatis-3/zh/sqlmap-xml.html

转载地址:http://kschl.baihongyu.com/

你可能感兴趣的文章
小程序瀑布流效果,解决左右两边高度差距过大的问题
查看>>
CentOS 7 更换 yum 源
查看>>
人工智能深度学习Caffe框架介绍,优秀的深度学习架构
查看>>
程序员编程10大哲理!血的教训,后人警惕!
查看>>
使用vue2+Axios遇到的一些坑
查看>>
解决 create-react-app IE 兼容性问题
查看>>
js数据结构-二叉树(二叉堆)
查看>>
都9102年了,还问Session和Cookie的区别
查看>>
this的指向(简单描述版)
查看>>
变量提升的原理
查看>>
【机器学习】机器学习简介
查看>>
我是如何在2年内逆袭成为BAT年薪40W的资深开发工程师的?
查看>>
当知识图谱遇上文本智能处理,会擦出怎样的火花?
查看>>
熟练使用C标签,EL表达式
查看>>
Vue(非)父子组件的传值以及方法调用
查看>>
React入门-3.组件
查看>>
【C++】 27_二阶构造模式
查看>>
SpringBoot之读取配置文件
查看>>
eosjs 文档(目录)
查看>>
我对函数式编程的理解
查看>>