MyBatis的批量更新

来源:互联网 发布:一卡易软件收费多少 编辑:程序博客网 时间:2024/06/05 09:16

MyBatis的批量更新有两种情况:

第一种:更新的字段值都是一样的(具体如下)

<update id="batchDeleteDuty" parameterType="java.util.List">  update DUTY set DUTY_NAME = #{dutyName} where DUTY_ID in  <foreach collection="dutyIds" item="id" index="index" open="(" close=")" separator=",">  #{id}  </foreach>  </update>

这种更新只能将符合条件的记录更新指定字段为相同的值。


第二种:更新是符合条件的记录更新为自己的值(实际也是多个update语句)

1:对于MySQL

修改数据库连接配置:&allowMultiQueries=true

比如:jdbc:mysql://192.168.1.236:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&allowMultiQueries=true

 <update id="batchUpdateDuty" parameterType="java.util.List">  <foreach collection="dutyList" item="duty" index="index" open="" close="" separator=";">  update DUTY D  <set>  <if test="duty.dutyClassId != null">  D.DUTY_CLASS_ID = #{duty.dutyClassId},  </if>  <if test="duty.restId != null">  D.REST_ID = #{duty.restId},  </if>  </set>  where D.DUTY_ID = #{duty.dutyId}  </foreach>  </update>
这样的更新就可以一次执行多条sql(注意:这是针对MySql的,oracle不适用)

2:对于oracle

直接在xml的Sql前后加上begin end 具体如下:

 <update id="batchUpdateDuty" parameterType="java.util.List">  begin  <foreach collection="dutyList" item="duty" index="index" open="" close="" separator=";">  update DUTY D  <set>  <if test="duty.dutyClassId != null">  D.DUTY_CLASS_ID = #{duty.dutyClassId},  </if>  <if test="duty.restId != null">  D.REST_ID = #{duty.restId},  </if>  </set>  where D.DUTY_ID = #{duty.dutyId}  </foreach>  ;end;  </update>


0 0
原创粉丝点击