有次需要完成一个功能的时候sql语句用到id NOT IN
一开始这个参数我在impl 用字符串拼接好了,如 (123,456,789)
通过dao层的mapper传入xml,运行后,报错
拉到下面看详细信息,
Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '' (13690,13693,13691,13692,13716,13714,13715,13718,13719,13720,13712,13713,13721' at line 3
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 xxxxxx
然后就不采用字符串先拼接好的方法,直接丢一个map进去循环遍历,在xml中完成拼接
接下来看看mybatis怎么完成map的循环遍历
使用<foreach></foreach>标签
看看这个标签中的参数
collection:这个是必要的参数,里面填在mapper里添加了@Param注解的名字,是我们foreach循环遍历的主体
index: 在数组里这个单词就是指索引,那么在map和list同理,指key,这个参数我们命名什么名字并不重要,重要是要知道它其实就是指map,list的key
item: 这个必要的参数。指map或list的value(值),同样,我们命名什么不重要
separator:分隔符。遍历过程中最终写入sql语句内容的分隔,用来分隔元素
open: 循环遍历的开始符号,开始时帮我们加上
close:循环遍历结束的符号,结束时帮我们加上
index,item要看实际情况,如果map或list里又嵌套了map或list,自己要清楚index,item指向的是什么类型
接下来看我的例子
我传入的map没有嵌套
mapper:
xml:
collection中填入@Param注解的名,index我就命名key,item我也直接用value命名