首页 > 其他分享 >mybatis批量插入,返回主键ID不成功,巨坑

mybatis批量插入,返回主键ID不成功,巨坑

时间:2022-09-27 20:58:29浏览次数:58  
标签:insert 巨坑 ID mybatis org entity 主键

一、场景说明

批量插入,返回主键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

标签:insert,巨坑,ID,mybatis,org,entity,主键
From: https://www.cnblogs.com/huozhonghun/p/16735940.html

相关文章