mybatis传入List实现批量更新的坑

 

免费chatgpt使用网址 http://ffff.chat:2023  在设置中设置userID

 

 

今天用mybatis实现批量更新,一直报错,说我的sql语句不对,然后我还到mysql下面试了,明明没问题,但就是过不去,原来问题在这。

 

 

在连接数据库的url中要加入?allowMultiQueries=true这段,而且要放在第一行

 

 然后dao层就如下写

 

最后mapper.xml就是正常的写法,解释一下,我的collection="list",为什么写list,因为传入的是一个list集合,这里必须写list,

如果传入一个数组比如Integer[],那么就要写collection="array"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 如果不是第一次参加考试,就更新学生的答案 -->
    <update id="updateStudentAnswer" parameterType="java.util.List">
        <if test="list!=null">
            <foreach collection="list" item="studentAnswer" index= "index" open="" close="" separator =";">
                update studentanswerinfo
                <set>
                    SAnswer=#{studentAnswer.SAnswer},
                    Getpoint=#{studentAnswer.Getpoint},
                    other=#{studentAnswer.other}
                </set>
                <where>
                    questionID=#{studentAnswer.questionID}
                </where>
            </foreach>
        </if>
    </update>

 

 

时隔一年,再次用mybatis批量插入List,在连接数据库的开头加入?allowMultiQueries=true 时,还是一直报这个错误

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 ';

 

 

今天在Stack Overflow上找到了另外一种解决办法,也不需要在连接数据库的url上加入?allowMultiQueries=true。原来出现这种原因,主要是批量插入list时,mysql是拼接sql语句,之前这样写,拼接会出现values后面会有空格等mysql不识别的sql语句。需要如下拼接

 

1
2
3
4
5
6
7
8
<insert id="insertRecords" parameterType="java.util.List">
            replace into bi_staff_skill_information
            (staff_id, skill_id, skill_level)values
            <foreach item="staffSkillInfo" index="index" collection="list"
                 open="(" separator="),(" close=")">
                #{staffSkillInfo.staffId},#{staffSkillInfo.skillId},#{staffSkillInfo.skillLevel}
            </foreach>
    </insert>

 

这样就实现了批量插入数据。同样遇到问题的大家,可以去试一试。有问题欢迎大家留言

 

 

最后附带字节跳动的内推码,第一张是校招内推码,第二张在校生日常实习和社招可以投递哦,有兴趣的小伙欢迎积极投递。

内推码:W9EG9W9。

 

 

 

posted @   my日常work  阅读(36722)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示