Oracle:Mysql数据库中的insertOrUpdateBatch方法 数据存在则更新:不存在则插入方法

作者:袖梨 2026-07-16

Oracle 数据库 和 Mysql 数据库 中的SQL 存在不同的方言,在写SQL时要注意区分

Oracle、Mysql数据库中的insertOrUpdateBatch方法(数据存在则更新,不存在则插入方法)

1. Orecal 数据库

Orecal 数据库的  insertOrUpdateBatch 是用 mege into 类实现的

// merge into 语法  当数据存在时 更新数据, 不能更新 指定主键字段 (判断数据是否存在的字段)merge into QWPH_XN.SYS_AREA   t1using (select 'lkz001' as ID,'KD001' as P_ID  from dual) t2on ( t1.ID = t2.ID and t1.P_ID = t2.P_ID)when matched then    update    set t1.AREA_NAME = 'lkz0016666666666666666666'when not matched then    insert (ID,P_ID)    values ('lkz002','KD001' );    //  ****  dual是一张临时表,也可以自己构建,例如:     merge into  QWPH_XN.SYS_AREA   t1using DUALon ( t1.ID= 'lkz003')when matched then    update    set t1.AREA_NAME = 'KEDONG'when not matched then    insert (ID,P_ID)    values ('lkz003','KD003' );
<!--   根据指定 字段 进行更新, 不能更新关联条件中的 字段       如果 更新字段 被 改动了,那就是 插入-->    <insert id="insertOrUpdateBatch">            <foreach collection="collectList" item="entity" separator=";">                merge into ${model}.SYS_AREA t1 using dual on (t1.ID = #{entity.id} and t1.P_ID = #{entity.pId})                when matched then                update                <set>                    <if test="entity.areaName != '' and  entity.areaName != null ">                        AREA_NAME = #{entity.areaName},                    </if>                    <if test="entity.dtype != '' and  entity.dtype != null ">                        DTYPE = #{entity.dtype},                    </if>                    <if test="entity.level != '' and  entity.level != null ">                        LEVEL = #{entity.level},                    </if>                    <if test="entity.datasourceId != '' and  entity.datasourceId != null ">                        DATASOURCE_ID = #{entity.datasourceId},                    </if>                </set>                when not matched then                insert (ID, AREA_NAME, P_ID, DTYPE, "LEVEL", DATASOURCE_ID)                values (#{entity.id}, #{entity.areaName},#{entity.pId},                #{entity.level},#{entity.dtype},#{entity.datasourceId})            </foreach>    </insert>

2. Mysql 数据库

Orecal 数据库 和 Mysql 数据库的 插入或更新 sql 语句 不一样

<!--insert into on duplicate key update表示插入更新数据,当记录中有PrimaryKey,或者unique索引的话,如果数据库已经存在数据,则用新数据更新(update),如果没有数据效果则和insert into一样。--><insert id="insertOrUpdateBatch"keyProperty="uuid"useGeneratedKeys="true">inSert intO TASK LOG(TASK_ID, TASK_NAME, EXEC TYPE, STATUS, EXEC_TIME, EXCEPTION_MESSAGE)values<foreach collection="entities" item="entity" separator=" ">(#lentity,taskId}, #entity.taskName}, #lentity.execType}, #ientity,status}, #entity.execTime}, #lentity.exceptionMessage})</foreach>on duplicate key updateTASK ID = ValUeS(TASK ID)TASK NAME = VLUeS(TASK NAME)EXEC TYPE = ValUeS(EXEC_TYPE)STATUS = valveS(STATUS).EXEC TIME = VlveS(EXEC TIME)EXCEPTION_MESSAGE = VaLUeS(EXCEPTION_MESSAGE)</insert>

总结 

相关文章

精彩推荐