Mybatis批量插入,返回主键ID不成功,巨坑记录
一、场景说明
批量插入,返回主键ID报错
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.binding.BindingException: Parameter ‘id’ not found. Available parameters are [entitys, param1]
二、代码
dao.java
int insertBatch(@Param("entitys") List<ForlanDTO> entities);dao.xml
<insert id="insertBatch" useGeneratedKeys="true" keyProperty="id">
insert into forlan_batch_insert(name,age)
values
<foreach collection="entitys" item="entity" index="index" separator=",">
(#{entity.name}, #{entity.age})
</foreach>
</insert>
mybatis版本号为:3.4.2
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency>
三、解决方案
1、换mybatis版本
调整版本号为3.5.2
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
换了版本号后,就正常了,其它版本大家可以测试下,具体从什么版本后修复的,这个暂时没查到
2、调整代码
dao.java
int insertBatch(@Param("list") List<ForlanDTO> entities);dao.xml
<insert id="insertBatch" useGeneratedKeys="true" keyProperty="id">
insert into forlan_batch_insert(name,age)
values
<foreach collection="list" item="entity" index="index" separator=",">
(#{entity.name}, #{entity.age})
</foreach>
</insert>
关键点:foreach里的collection必须是list,不然就会报错
四、拓展说明
关于返回主键ID,需要在insert标签中添加,useGeneratedKeys=“true” keyProperty=“id”,useGeneratedKeys和keyProperty必须配合使用,keyProperty的字段就是返回的主键ID
mybatis3.3.1及以上的版本,才支持批量插入返回主键ID
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
java高效打印一个二维数组的实例(不用递归,不用两个for循环)
下面小编就为大家带来一篇java高效打印一个二维数组的实例(不用递归,不用两个for循环)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-03-03
SpringBoot使用SensitiveWord实现敏感词过滤
这篇文章主要为大家详细介绍了SpringBoot如何使用SensitiveWord实现敏感词过滤功能,文中示例代码讲解详细,感兴趣的小伙伴可以了解一下2023-01-01
启动 Eclipse 弹出 Failed to load the JNI shared library jvm.dll
这篇文章主要介绍了有时候,新电脑上回碰到打开Eclipse时,弹出提示“Failed to load the JNI shared library jvm.dll”错误,这里给大家分享解决方案2016-08-08
java 通过发送json,post请求,返回json数据的方法
下面小编就为大家分享一篇java 通过发送json,post请求,返回json数据的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-03-03


最新评论