Service
public boolean foreachinsert(Test2 test) {
// TODO Auto-generated method stub
List<Test2> list = new ArrayList<>();
Test2 t = null;
try {
for(int i = 0;i<6;i++){
t = new Test2();
t.setId(i);
t.setAge(i+"");
t.setName(i+"");
list.add(t);
}
System.out.println("i am list list lsit list *************"+list.toString());
empMapper.foreachinsert(list);
return true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}
mapper
//批量增加
public void foreachinsert(List<Test2> item);
xml
<insert id="foreachinsert" parameterType="java.util.List">
INSERT INTO TX_TEST (NAME,AGE)
<foreach close=")" collection="list" item="item" open="(" separator="union all">
select
#{item.name},#{item.age}
from dual
</foreach>
</insert>
稍微改进下可以这么写
<insert id="foreachinsert" parameterType="java.util.List">
INSERT INTO TX_TEST (NAME,AGE)
<foreach close=")" collection="list" item="item" open="(" separator="union all">
select
<if test="item.name != null and item.name != ''">
#{item.name},
</if>
<if test="item.name == null or item.name == ''">
null,
</if>
<if test="item.age != null and item.age != ''">
#{item.age}
</if>
<if test="item.age == null or item.age == ''">
null
</if>
from dual
</foreach>
</insert>