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>
调整版本号为3.5.2
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
换了版本号后,就正常了,其它版本大家可以测试下,具体从什么版本后修复的,这个暂时没查到
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