MyBatis 如何传递参数(全)
发布日期:2021-06-30 17:39:29 浏览次数:2 分类:技术文章

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

一、单个参数:

public List
findXXBeanList(String xxCode);

其中方法名和ID一致,#{}中的参数名与方法中的参数名一直, 我这里采用的是XXXBean是采用的短名字,

select 后的字段列表要和bean中的属性名一致, 如果不一致的可以用 as 来补充。

 

二、多参数:

public List
getXXXBeanList(String xxId, String xxCode);
由于是多参数那么就不能使用parameterType, 改用#{index}是第几个就用第几个的索引,索引从0开始

三、Map封装多参数: 

public List
getXXXBeanList(HashMap map);
其中hashmap是mybatis自己配置好的直接使用就行。map中key的名字是那个就在#{}使用那个,map如何封装就不用了我说了吧。

 四、List封装in:

public List
getXXXBeanList(List
list);
foreach 最后的效果是select 字段... from XXX where id in ('1','2','3','4')

五、多参数传递之注解方式示:    

public AddrInfo getAddrInfo(@Param("corpId")int corpId, @Param("addrId")int addrId);
以前在

六、selectList()只能传递一个参数,但实际所需参数既要包含String类型,又要包含List类型时的处理方法:

List
list = new ArrayList
();list.add("1");list.add("2");Map
map = new HashMap
();map.put("list", list); //网址idmap.put("siteTag", "0");//网址类型
public List
getSysInfo(Map
map) {  return getSqlSession().selectList("sysweb.getSysInfo", map);}

知识点 - #{} 和 ${} 的区别:

1、#{}能防止sql注入,${}不能防止sql注入;

 2、${}一般用来传入数据库对象,如:数据表名;

3、在使用order  by 时使用${},因为传入参数为动态参数。

4、#{}表示一个占位符号,#{}接收输入参数,类型可以是简单类型,pojo、hashmap。  如果接收简单类型,#{}中可以写成value或其它名称。 #{}接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。

5、${}表示一个拼接符号,会引用sql注入,所以不建议使用${}。  ${}接收输入参数,类型可以是简单类型,pojo、hashmap。如果接收简单类型,${}中只能写成value。${}接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。

Mybatis官方说明:

String Substitution  By 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.  

参考:

转载地址:https://lemonstone.blog.csdn.net/article/details/86363178 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:HTTP状态码
下一篇:设计模式 享元模式

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月14日 03时47分38秒