Mybatis 批量更新 PostgreSQL 数据库,返回更新行数

1. 拼接成1条sql语句,可返回修改行数。

PostgreSQL的批量更新原生sql:

update person
set 
    name=tmp.name,
    age=tmp.age,
    addr=tmp.addr,
    num=tmp.num,
    update_time=tmp.update_time
 from (
     values
     (1,'关羽',43,'成都',1,'2021-03-26 17:32:28'),
     (2,'张飞',37,'成都',2,'2021-03-26 17:32:28'),
     (3,'赵云',33,'成都',3,'2021-03-26 17:32:28'),
     (4,'马超',31,'成都',4,'2021-03-26 17:32:28'),
     (5,'黄忠',49,'成都',5,'2021-03-26 17:32:28')
 ) as
     tmp(id,name,age,addr,num,update_time)
 where
     person.id=tmp.id

在Mybatis的xml中的sql写法:

<update id="batchUpdate">
    update person
    set
        name=tmp.name,
        age=tmp.age,
        addr=tmp.addr,
        num=tmp.num,
        update_time=tmp.update_time
    from (
        values
        <foreach collection="list" item="item" separator=",">
            (
            #{item.id},
            #{item.name},
            #{item.age},
            #{item.addr},
            #{item.num},
            cast(#{item.updateTime} as timestamp)
            )
        </foreach>
    ) as
        tmp(id,name,age,addr,num,update_time)
    where
        spares_stocktaking_detail.detail_id = temp.detail_id
</update>

其中,cast(#{item.updateTime} as timestamp) 将数据类型转为时间格式。

2. 执行多条sql语句,分号分隔。成功只返回1。

<update id="batchUpdate">
    <foreach collection="list" item="item" separator=";">
        update person
        set
            name = #{item.name},
            age = #{item.age},
            addr = #{item.addr},
            num = #{item.num},
            update_time = #{item.updateTime}
        where
            id = #{item.id}
    </foreach>
</update>
posted @ 2024-02-28 15:15  cralor  阅读(325)  评论(0编辑  收藏  举报