记录一个mybatis-plus的批量修改的问题

使用@Update注解加<foreach>标签拼接sql语句

方式一

@Update({"<script>" +
                "<foreach collection = \"xxxs\" item = \"xxx\" separator = \";\">" +
                    "update `table_name` set `user` = #{xxx.user} where `id` = #{xxx.id} " +
                "</foreach>" +
            "</script>"})
    public void updateBatchSubConfig(List<xxx> xxxs);

使用这个方式当list的size等于1的时候没有问题,一旦size数量大于1就会报语法问题如下


### Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update `table` set `user` = '1' where `id` = 2' at line 1
### The error may exist in com/sioo/agent/database/mapper/AgentMessageSubConfigMapper.java (best guess)
### The error may involve com.sioo.agent.database.mapper.AgentMessageSubConfigMapper.updateBatchSubConfig-Inline
### The error occurred while setting parameters
### SQL: update `table` set `user` = ? where `id` = ?  ; update `agent_message_sub_config` set `user` = ? where `id` = ?
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update `table` set `user` = '1' where `id` = 2' at line 1
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update `table` set `user` = '1' where `id` = 2' at line 1

始终没研究出来是什么问题导致的,所以改成其他方式执行。

方式二

@Update({"<script>" +
            " update `table`" +
                " <trim prefix=\"set\" suffixOverrides=\",\">" +
                    " <trim prefix=\"user = case\" suffix=\"end,\">" +
                        "<foreach collection = \"xxxs\" item = \"xxx\" index=\"index\">" +
                            " when id = #{xxx.id} then #{xxx.acceptUser}" +
                        "</foreach>" +
                    "</trim>" +
                "</trim>" +
            "where " +
                "<foreach collection=\"xxxs\" separator=\"or\" item=\"xxx\" index=\"index\">" +
                    "id = #{xxx.id}" +
                "</foreach>" +
            "</script>"})
    public void updateBatchSubConfig(List<xxx> xxxs);

就相当于下面的语法,如果id等于1,user就等于name1,如果id等于2,user就等于name2

 UPDATE table
    SET user = CASE id 
        WHEN 1 THEN 'name1'
        WHEN 2 THEN 'name2'
        WHEN 3 THEN 'name3'
    END
WHERE id IN (1,2,3)

这样就可以批量修改了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值