使用@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)
这样就可以批量修改了