One - One Code All

Blog Content

SSM-Mybatis保存多条记录,foreach循环列表和数组select in

Java   2018-03-14 22:05:36

在Mybatis的xml配置中使用集合,主要是用到了foreach动态语句。

foreach的参数:

foreach元素的属性主要有 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名.
index指定一个名字,用于表示在迭代过程中,每次迭代到的位置.
open表示该语句以什么开始

separator表示在每次进行迭代之间以什么符号作为分隔符.

close表示以什么结束.


通过foreach的方法来实现,这里我们巧妙的利用了sql的语法规则用Mybatis的foreach动态语句来处理。

java代码:

public abstract void saves(@Param("tables")List tables);

xml代码:

insert into table(name,addtime) values  
    (#{item.name},#{item.addtime})

以上方法Mybatis会帮我们进行sql注入拦截,Mybatis如果采用#{xxx}的形式设置参数,Mybatis会进行sql注入的过滤。如果采用的是${xxx},Mybatis不会进行sql注入过滤,而是直接将参入的内容输出为sql语句。

判断集合是否有值

0">



Mybatis生成select * from table where id in(1,2,...,n)语句的查询

我们一般的做法是在方法的参数处指定传入的参数名称,在xml中使用的时候,集合的名称要和方法的Param的名称一致,这样便于阅读和理解,

然后是在对应的xml文件中使用foreach循环。

java代码如下:

public abstract List findByIds(@Param("ids")List ids);

对应的xml代码如下:

select * from table
    id in #{item}



上一篇:SSM-Mybatis实现select in 查询
下一篇:GitHub项目:自然语言处理领域的相关干货整理

The minute you think of giving up, think of the reason why you held on so long.