MyBatis MySQL 实现批量不存在则插入,存在则更新

在日常开发中,需要从数据库中批量导入所有数据,同时这些数据可能在目标表中存在,也可能不存在。因为数据量还比较大,如果一条一条在业务代码里判断然后插入或者更新,非常非常慢。

这个时候,我们可以对判断【数据是否存在】的字段建立UNIQUE索引,然后使用如下的方式,进行批量地插入/更新

<insert id="insertBatch" >
      INSERT INTO table(org_id, org_name, org_fullid, org_fullname, creator, gmt_create, modifier)
      VALUES
      <foreach collection="allCollections" separator="," item="fullIdOrg">
        (
        #{fullIdOrg.orgId},
        #{fullIdOrg.orgName},
        #{fullIdOrg.orgFullid},
        #{fullIdOrg.orgFullname},
        #{fullIdOrg.creator},
        #{fullIdOrg.gmtCreate},
        #{fullIdOrg.modifier}
        )
      </foreach>
        ON DUPLICATE KEY UPDATE
        org_fullid=VALUES(org_fullid),
        org_name=VALUES(org_name),
        org_fullname=VALUES(org_fullname),
        modifier=VALUES(modifier)
    </insert>

这边UPDATE的字段不需要和INSERT语句的字段对应,foreach中迭代的变量也可以在循环外获取到。

因为是跨数据源,所以这边用到了一个foreach的迭代,如果是单数据源,应该可以用INSERT INTO (,) VALUE (SELECT xxx FROM xxx) 代替

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于MybatisMySQL批量插入批量更新,可以使用以下方法: 1. 批量插入 使用MyBatis的foreach标签,可以很方便地实现批量插入操作。示例如下: ```xml <insert id="batchInsert" parameterType="java.util.List"> insert into my_table (col1, col2, col3) values <foreach collection="list" item="item" separator=","> (#{item.col1}, #{item.col2}, #{item.col3}) </foreach> </insert> ``` 其中,parameterType指定参数类型为List,collection属性指定要插入的List对象,item指定List中的元素,separator指定分隔符。 在Java代码中,调用该方法时,将List对象作为参数传入即可。 2. 批量更新 对于批量更新,可以使用MySQL的replace into语句来实现。示例如下: ```xml <update id="batchUpdate" parameterType="java.util.List"> <foreach collection="list" item="item" separator=";"> replace into my_table (id, col1, col2, col3) values (#{item.id}, #{item.col1}, #{item.col2}, #{item.col3}) </foreach> </update> ``` 其中,replace into语句会先尝试插入记录,如果记录存在,则更新记录。参数类型和调用方式与批量插入相同。 3. 存在更新 如果只想更新存在记录,可以使用MySQL的on duplicate key update语句。示例如下: ```xml <update id="updateIfExists" parameterType="com.example.MyEntity"> insert into my_table (id, col1, col2, col3) values (#{id}, #{col1}, #{col2}, #{col3}) on duplicate key update col1 = values(col1), col2 = values(col2), col3 = values(col3) </update> ``` 其中,id字段为主键。如果该记录存在,则更新col1、col2、col3字段;否则插入记录。参数类型为MyEntity,调用方式为传入一个MyEntity对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值