今天用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>
這樣就實現了批量插入數據。同樣遇到問題的大家,可以去試一試。有問題歡迎大家留言
