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"

<!-- 如果不是第一次参加考试,就更新学生的答案 -->
	<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语句。需要如下拼接

 

<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 @ 2018-07-20 16:43  my日常work  阅读(36688)  评论(1编辑  收藏  举报