多参数传入 interfaceName(Map<String,String> map); 因为mysql中可以引成字符串
==> Preparing: update user set id=? where name=? and pwd=?
==> Parameters: 111(String), 1(String), 1(String)
<== Updates: 1
#{}和${}的区别是什么?
网上的答案是:#{}占位符 是预编译处理,${}是字符串替换。mybatis在处理#{}时,会将sql中的#{}替换为?号,调用PreparedStatement的set方法来赋值;mybatis在处理${}时,就是把${}替换成变量的值。使用#{}可以有效的防止SQL注入,提高系统安全性。
对于这个题目我感觉要抓住两点:
(1)$符号一般用来当作占位符,常使用Linux脚本的人应该对此有更深的体会吧。既然是占位符,当然就是被用来替换的。知道了这点就能很容易区分$和#,从而不容易记错了。
(2)预编译的机制。预编译是提前对SQL语句进行预编译,而其后注入的参数将不会再进行SQL编译。我们知道,SQL注入是发生在编译的过程中,因为恶意注入了某些特殊字符,最后被编译成了恶意的执行操作。而预编译机制则可以很好的防止SQL注入。
https://www.cnblogs.com/xxj-bigshow/p/10477359.html
个人实践补充:
map.xml
<select id="getUserListBy2Param" resultType="uu">
select * from mybatis.user
<where> <!-- 小于:< -->
and id < #{id} and name #{name}
</where>
</select>
@Test
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserListBy2Param(5, "like '%asd%' ");
${} 字符串替换
编译通过
#{} 预编译,占位符,防止sql注入
报错, Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''like \'%asd%\' '' at line 4
-----------------------------------
当我们传入的字符串是1,3,5,7的时候,用#只能删除id为1的品牌,其他的就不能删除了,这是因为,使用了#,就是一个占位符了,经过编译后是
where id in(?) 加入字符串后是 where id in('1,3,5,7') 这种,在SQL中就只会删除一个,我们来看SQL的执行效果
解决: select * from user where FIND_IN_SET(name,#{ids})
mapper.queryUserByIdIn("1,asd,3,4");