一、问题描述
前段时间主要再用spring data jpa,最近又回到了mybatis的使用上,发现好多东西都忘了。
然后编写批量更新语句时候,发现老是更新失败,但是从控制台获取的sql语句又能够在数据库中正常执行,这个小坑让我花了些时间,为了避免以后再犯错,在此这里来记录下解决办法。
二、报错信息
注:在使用本方案解决问题之前,你首先要确定你的批量更新sql是否是正确的,如何确认呢?很简单把控制台打印的语句参数替换后,放到数据库执行一下,看是否能成功执行。
如果你使用的是开发工具是IDEA的话,顺便推荐一款查看执行sql的插件:MyBatis Log Plugin。
可以使用IDEA直接安装使用。
:
### Error updating database. Cause: : 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 mall_product
三、项目代码
ProductMapper:
public interface ProductMapper {
int batchUpdate(@Param("products") List<Product> products);
}
Mybatis Sql:
<update id="batchUpdate" parameterType="list">
<foreach collection="products" item="item" index="index" open="" close="" separator=";">
update mall_product
<set>
<if test=" != null">
category_id = #{,jdbcType=INTEGER},
</if>
<if test=" != null">
name = #{,jdbcType=VARCHAR},
</if>
<if test=" != null">
subtitle = #{,jdbcType=VARCHAR},
</if>
<if test=" != null">
main_image = #{,jdbcType=VARCHAR},
</if>
<if test=" != null">
sub_images = #{,jdbcType=VARCHAR},
</if>
<if test=" != null">
detail = #{,jdbcType=VARCHAR},
</if>
<if test=" != null">
price = #{,jdbcType=DECIMAL},
</if>
<if test=" != null">
stock = #{,jdbcType=INTEGER},
</if>
<if test=" != null">
status = #{,jdbcType=INTEGER},
</if>
</set>
where id = #{,jdbcType=INTEGER}
</foreach>
</update>
四、解决方案
其实这个错误就是源于mybatis默认是不支持批量更新的,
如果想要进行批量更新,需要在连接数据库的地址上加一个配置,内容如下:
allowMultiQueries=true
我的中关于数据库的配置。
spring:
datasource:
type:
#MySQL配置
driver-class-name:
url: jdbc:mysql://localhost:3306/mall?allowMultiQueries=true&useUnicode=yes&characterEncoding=UTF-8&useInformationSchema=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
username: root
password: 123456
改好了之后,就可以重新尝试了,小伙伴一定要保证你的sql本身没有错误啊。