最近在用mybatis3做项目,需要很多的批量操作,所以就写了一些Demo,同时分享给大家,希望对您有用j_0028.gif


首先说一下foreach标签中几个重要的属性的含义:

字段名
含义
item
指集合里面的数据项对象,如果是List,则表示list中所代表的对象。例如:如果存在List<Student>这个集合,那么item就代表student对象;
collection
可以使list/arrays,如果list在map对象中最为参数传递过来,那么该属性的值就是list对象在map中所对应key;例如:Map<String,List<String>>对象中存在key=ids,value=ArrayList<Sting>的键值对,那么collection对应的值应该是ids;
separator
指定集合中元素之间的分隔符
open
在foreach所包含的sql语句的开始加入指定的字符
close
在foreach所包含的sql语句的结束加入指定的字符


批量插入:

<insert id="insertStudentMany" parameterType="java.util.List">
        insert into student(name,sex) values
        <foreach item="item" collection="list" index="index"
            separator=",">
            (#{item.name},#{item.sex})
        </foreach>

</insert>

批量更新:

<update id="updateName" parameterType="java.util.Map">
      
      <foreach item="item" collection="stu" index="index"
            separator=";">
            update student
         <set>
            name=#{item.name}
         </set>
         where id =#{item.id}
      </foreach>
</update>

注意此处的分隔符即separator必须是;即表示多条sql语句之间的分隔符


具体可以看附件,附件是一个基于cxf的restful的测试例子。只需要放入tomcat或者其他容器中即可。


附件×××地址:http://down.51cto.com/data/1883769