`

mybatis批量操作三种方法

阅读更多
mybatis批量操作三种方法
一:批量更新某一个字段(数组或者map作为参数)
<update id="updateInvoiceID" parameterType="java.util.Map" >
update table
set
<if test="parentID != null and parentID !=''">
parentID= #{parentID}
</if>
where SUA_TransItemID in
<foreach collection="sUATransItemIDs" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
</update>

二:批量新增或者批量修改(固定字段,不带条件,foreach放在执行内)
List<Map<String ,Object>> list = new ArrayList<Map<String ,Object>>();//作为参数
<insert id="insertBatch" parameterType="java.util.List">
insert into table(
xxx,
yyy,
zzz,
createTime
)values
<foreach collection="list" item="item" index="index"
separator=",">
(
#{item.xxx},
#{item.yyy},
                        #{item.zzz},
date_format( now()
,'%Y%m%d%H%i%s')
)
</foreach>
</insert>

三:批量新增或者批量修改(不固定字段,带if test条件,foreach放在执行外)
List<Map<String ,Object>> list = new ArrayList<Map<String ,Object>>();//作为参数
<insert id="insert" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close=";" separator=";">
insert table(
<if test="item.remark!=null and item.remark!=''">
remark,
</if>
createTime
)values
(
<if test="item.remark!=null and item.remark!=''">
#{item.remark},
</if>
date_format( now() ,'%Y%m%d%H%i%s')
)
</foreach>
</insert>

总结:(1)item:循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。
具体说明:在list和数组中是其中的对象,在map中是value。
该参数为必选。
(2)separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
(3)open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选。
(4)close:foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
(5)index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics