关于mybatis-plus 中saveOrUpdateBatch的方法重写,不根据主键更新,mysql中主键使用自动填充UUID

mybatis-plus 中saveOrUpdateBatch都是采用默认策略(主键)作为判断该数据存在与否的依据,当我们需要使用其他字段作为判断条件的时候,发现不论怎么使用都不行。

 

 

这个时候可以采取简单的方式,list在代码里面循环里面使用saveOrUpdate来进行一条一条更新,但是一条一条更新会太慢,当数据太大时也是不行的。

所以这里采用自己重写saveOrUpdateBatch方式进行实现:

Oracle数据库:

<update id="saveOrUpdateBatch">
        MERGE INTO t_oe_type t1
        USING (
        <foreach collection="list" item="item" index="index" separator="union">
            SELECT
            #{item.CategoryId} as category_id,
            #{item.CategoryName} as category_name,
            #{item.Brands}as brands
            FROM DUAL
        </foreach>
        ) t2
        on (t1.category_id=t2.category_id)
        WHEN MATCHED THEN
        UPDATE SET t1.category_name=t2.category_name,t1.brands=t2.brands
        WHEN NOT MATCHED THEN
        INSERT ( category_id,
        category_name,
        brands) VALUES (t2.category_id,t2.category_name,t2.brands)
    </update>

这里是采用oracle独有的 MERGE INTO xxxtable 表1 USING 数据源 表2  on 条件 来创建一个临时表与原来的数据进行对比,这时候使用MATCHED关键字来看是否匹配上了,匹配上了则使用update语句没有匹配上则使用insert语句。

但是这个方法在orcale数据库中可以进行使用,但是在mysql中不行,因为mysql中没有  MERGE INTO USING 这个语法,这时候我们需要重新换个思路去解决

mysql数据库:

<update id="saveOrUpdateBatch">
        INSERT INTO t_oe_type ( category_id, category_name, brands ) select * from (
        <foreach collection="list" item="item" index="index" separator="union">
            SELECT
            #{item.CategoryId} as category_id,
            #{item.CategoryName} as category_name,
            #{item.Brands}as brands
            FROM DUAL
        </foreach>
       ) t2
    on duplicate KEY UPDATE category_name
= t2.category_name,brands = t2.brands </update>

mysql因为没有 MERGE INTO USING 这个语法 所以我们采用mysql特有的 on duplicate KEY UPDATE 来进行数据处理,这样也可以实现saveOrUpdateBatch操作,但是这个有一个限制条件,那就是当前传入参数中必须要有一列是主键或UNIQUE索引否则的话会寻找不到对比数据,那么会就只会进行新增操作。

 重写saveOrUpdate后mysql中主键使用自动填充UUID

select replace(uuid(),"-","") as uuid;

这个可以实现uuid自动生成,但是需要自己带入insert 或者update语句中:

        INSERT INTO t_oe_type ( id,category_id, category_name, brands,products ) select * from (
        <foreach collection="list" item="item" index="index" separator="union">
            SELECT
            (select replace(uuid(),"-","") as uuid) id,
            #{item.CategoryId} as category_id,
            #{item.CategoryName} as category_name,
            #{item.Brands} as brands,
            #{item.products} as products
            FROM DUAL
        </foreach>
       ) t2 on duplicate KEY UPDATE brands = t2.brands,products=t2.products

这种方法去进行更新的话,只会根据唯一索引去更新,不会根据主键更新。

此方法自用,欢迎指正!

 

posted @ 2022-05-21 16:19  牧雨  阅读(20182)  评论(0编辑  收藏  举报