`
geeksun
  • 浏览: 953025 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

MyBatis 批量操作

阅读更多
       使用MyBatis做数据处理框架时,操作大量数据的插入、更新等耗时的工作时,可以使用批量处理来提高效率,MyBatis的批量处理主要使用foreach标签来实现。
 

        foreach 元素的功能是非常强大的,它允许你指定一个集合,声明可以用在元素体内的集合项和索引变量。它也允许你指定开闭匹配的字符串以及在迭代中间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。

 

        注意: 你可以将任何可迭代对象(如列表、集合等)和任何的字典或者数组对象传递给foreach作为集合参数。当使用可迭代对象或者数组时,index是当前迭代的次数,item的值是本次迭代获取的元素。当使用字典(或者Map.Entry对象的集合)时,index是键,item是值。
 
foreach入参介绍:
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list。
2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array。
3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map。
 
下面以博客的Post类为例,Post有3个属性:id、msg、type。
1.批量查询
<select id="selectPostBatch" resultType="domain.blog.Post">
  SELECT * FROM POST 
  WHERE id in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>
 
2.批量插入
<insert id="savePostBatch" parameterType="list">
  insert into POST 
  (msg,type)
  values
    <foreach item="item" index="index" collection="list" separator=",">
        #{item.msg},#{item.type}
  </foreach>
</insert>
 
3.批量更新
<update id="updatePostBatch" parameterType="list">
       <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update post
        <trim prefix="set" suffixOverrides=",">
            <if test="item.msg!=null">
                msg=#{item.msg},
            </if>
            <if test="item.type!=null">
                type=#{item.type},
            </if>
        </trim>
        where id=#{item.id}
        </foreach>
</update>
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics