根据主键(可多个)有数据则更新,无数据则插入,方便快捷。避免书写实体类
1、在mapper接口内容
/**
* 更新或插入操作
* primaryKey 主键字段
* tableName 表名
* maps 需要插入的值
*/
int insertOrUpdateListMapsBatch(@Param("tableName") String tableName, @Param("maps") List<LinkedHashMap<String, Object>> maps,@Param("primarysKey") List<String> primarysKey);
2、xml内容
<insert id="insertOrUpdateListMapsBatch">
<foreach collection="maps" item="map" separator=";">
MERGE INTO ${tableName} AS target USING ( VALUES
<foreach item="value" index="key" collection="map.entrySet()" open="(" separator="," close=")">
#{value}
</foreach>
) AS source
<foreach item="value" index="key" collection="map.entrySet()" open="(" separator="," close=")">
${key}
</foreach>
ON
<foreach item="value" index="key" collection="primarysKey" open="(" separator="," close=")">
target.${value} = source.${value}
</foreach>
WHEN MATCHED THEN
UPDATE SET
<foreach item="value" index="key" collection="map.entrySet()" separator=",">
target.${key} = #{value}
</foreach>
WHEN NOT MATCHED THEN
insert
<foreach item="value" index="key" collection="map.entrySet()" open="(" separator="," close=")">
${key}
</foreach>
values
<foreach item="value" index="key" collection="map.entrySet()" open="(" separator="," close=");">
source.${key}
</foreach>
</foreach>
</insert>