MyBatis 中 ${}和 #{}的正确使用方法(千万不要乱用)
1、#{}是预编译处理,MyBatis在处理#{}时,它会将sql中的#{}替换为?,然后调用PreparedStatement的set方法来赋值,传入字符串后,会在值两边加上单引号,如上面的值“4,44,514”就会变成“‘4,44,514'”;
2、
是 字 符 串 替 换 , 在 处 理 是 字 符 串 替 换 , M y B a t i s 在 处 理 时 , 它 会 将 s q l 中 的{}是字符串替换,在处理{}是字符串替换,MyBatis在处理{}时,它会将sql中的是字符串替换,在处理是字符串替换,MyBatis在处理时,它会将sql中的{}替换为变量的值,传入的数据不会加两边加上单引号。
注意:使用${}会导致sql注入,不利于系统的安全性!SQL注入:就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令。常见的有匿名登录(在登录框输入恶意的字符串)、借助异常获取数据库信息等
packagecom.xiaobu.mapper; importcom.xiaobu.base.mapper.MyMapper; importcom.xiaobu.entity.Country; importjava.util.List; /** *@authorxiaobu *@versionJDK1.8.0_171 *@dateon2018/11/2719:21 *@descriptionV1.0 */ publicinterfaceCountryMapperextendsMyMapper{ /** *功能描述:通过#{}来进行查询 * *@paramidsid *@returnjava.util.List *@authorxiaobu *@date2019/7/2611:53 *@version1.0 */ List findList(Stringids); /** *功能描述:通过${}来进行查询 * *@paramidsid *@returnjava.util.List *@authorxiaobu *@date2019/7/2611:53 *@version1.0 */ List findList2(Stringids); /** *功能描述:通过foreach来进行查询 * *@paramidsid *@returnjava.util.List *@authorxiaobu *@date2019/7/2611:53 *@version1.0 */ List findListByForEach(List ids); }
select*fromcountrywhereidin(#{ids}) select*fromcountrywhereidin(${ids}) select*fromcountrywhereidin #{item}
@Test publicvoidcountTotal(){ //统计总数SELECTCOUNT(Id)FROMcountry Exampleexample=newExample(City.class); intcount=countryMapper.selectCountByExample(example); System.out.println("count="+count); //按条件查询SELECTCOUNT(Id)FROMcountry Countrycountry=newCountry(); //country.setCountryname("1234"); intconunt2=countryMapper.selectCount(country); System.out.println("conunt2="+conunt2); } @Test publicvoidfindList(){ //Preparing:select*fromcountrywhereidin('1,2,3') Listcountries=countryMapper.findList("1,2,3"); //countries=[Country(countryname=Angola,countrycode=AO)] System.out.println("countries="+countries); //报错Thereisnogetterforpropertynamed'ids'in'classjava.lang.String List countries2=countryMapper.findList2("1,2,3"); System.out.println("countries2="+countries2); } @Test publicvoidfindListByForeach(){ //Preparing:select*fromcountrywhereidin(?,?,?) //Parameters:1(Integer),2(Integer),3(Integer) List list=newArrayList<>(3); list.add(1); list.add(2); list.add(3); List countries2=countryMapper.findListByForEach(list); System.out.println("countries2="+countries2); }
foreach说明
- item表示集合中每一个元素进行迭代时的别名,
- index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
- open表示该语句以什么开始,
- separator表示在每次进行迭代之间以什么符号作为分隔符,
- close表示以什么结束。
- collection指参数类型
到此这篇关于MyBatis中${}和#{}的正确使用方法(千万不要乱用)的文章就介绍到这了,更多相关MyBatis${}和#{}内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!