java通过mybatis实现通用数据更新/插入,向mapper中传入表名,map(字段名,字段值),自动执行对此表的更新/插入(通用merge into语句)。

  • 确认表内没有重复数据的前提下,可以直接采用全量数据的直接插入。
  1. 将数据打包为map<String, Object>后,执行数据插入。使用object方便数据类型映射,好比日期字段,可以格式化为date类型后,put进map中去。

mapper接口

// 根据map插入数据
Integer InsertByMap(@Param("tablename") String tablename,
                       @Param("map") Map<String, Object> map);

xml

<!-- 根据map插入数据 -->
<insert id="InsertByMap" parameterType="java.lang.String">
    INSERT INTO ${tablename}
    <foreach collection="map.entrySet()" index="key" separator="," open="(" close=")">
        ${key}
    </foreach>
    VALUES
    <foreach collection="map.entrySet()" item="val" separator="," open="(" close=")">
        #{val}
    </foreach>
</insert>
  1. 将数据打包为List<String, Object>后,执行数据插入。

mapper接口

// 根据list插入数据[keyList - 字段名; valList - 字段对应值]
Integer InsertByList(@Param("tablename") String tablename,
                       @Param("keyList") List<String> keyList,
                       @Param("valList") List<Object> valList);

xml

<!-- 根据list插入数据[keyList - 字段名; valList - 字段对应值] -->
<insert id="InsertByList" parameterType="java.lang.String">
    INSERT INTO ${tablename}
    <foreach collection="keyList" item="key" separator="," open="(" close=")">
        ${key}
    </foreach>
    VALUES
    <foreach collection="valList" item="val" separator="," open="(" close=")">
        #{val}
    </foreach>
</insert>
  1. 将数据拆为keymap和map后执行更新或插入操作(merge into),要求插入表有主键。

mapper接口

// 根据keymap,map插入或更新数据[keymap为主键字段,map为剩余字段]
Integer updateAndInsertByMap(@Param("tablename") String tablename,
                        @Param("keymap") Map<String, Object> keymap,
                        @Param("map") Map<String, Object> map);

xml

<!-- 根据keymap,map插入或更新数据[keymap为主键字段,map为剩余字段] -->
<update id="updateAndInsertByMap" parameterType="java.lang.String">
    MERGE INTO ${tablename} T
    USING (SELECT
    <foreach collection="keymap.entrySet()" index="key" item="val" separator=",">
        &apos;${val}&apos; ${key}
    </foreach>
    FROM DUAL) S ON ( 1=1
    <foreach collection="keymap.entrySet()" index="key">
        AND T.${key} = S.${key}
    </foreach>
    )
    when matched then
    update set
    <foreach collection="map.entrySet()" index="key" item="val" separator=",">
        T.${key} = #{val}
    </foreach>
    when not matched then
    insert
    <foreach collection="keymap.entrySet()" index="key" separator="," open="(" close=",">
        ${key}
    </foreach>
    <foreach collection="map.entrySet()" index="key" separator="," close=")">
        ${key}
    </foreach>
    values
    <foreach collection="keymap.entrySet()" item="val" separator="," open="(" close=",">
        #{val}
    </foreach>
    <foreach collection="map.entrySet()" item="val" separator="," close=")">
        #{val}
    </foreach>
</update>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐