Mybatis批量插入,返回主鍵ID不成功,巨坑記錄
一、場(chǎng)景說明
批量插入,返回主鍵ID報(bào)錯(cuò)
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版本號(hào)為:3.4.2
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency>
三、解決方案
1、換mybatis版本
調(diào)整版本號(hào)為3.5.2
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
換了版本號(hào)后,就正常了,其它版本大家可以測(cè)試下,具體從什么版本后修復(fù)的,這個(gè)暫時(shí)沒查到
2、調(diào)整代碼
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>
關(guān)鍵點(diǎn):foreach里的collection必須是list,不然就會(huì)報(bào)錯(cuò)
四、拓展說明
關(guān)于返回主鍵ID,需要在insert標(biāo)簽中添加,useGeneratedKeys=“true” keyProperty=“id”,useGeneratedKeys和keyProperty必須配合使用,keyProperty的字段就是返回的主鍵ID
mybatis3.3.1及以上的版本,才支持批量插入返回主鍵ID
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
springboot vue完成發(fā)送接口請(qǐng)求顯示響應(yīng)頭信息
這篇文章主要為大家介紹了springboot+vue完成發(fā)送接口請(qǐng)求顯示響應(yīng)頭信息,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Java實(shí)現(xiàn)讀取及生成Excel文件的方法
這篇文章主要介紹了Java實(shí)現(xiàn)讀取及生成Excel文件的方法,結(jié)合實(shí)例形式分析了java通過引入第三方j(luò)ar包poi-3.0.1-FINAL-20070705.jar實(shí)現(xiàn)針對(duì)Excel文件的讀取及生成功能,需要的朋友可以參考下2017-12-12
關(guān)于Java創(chuàng)建線程的2種方式以及對(duì)比
這篇文章主要給大家介紹了關(guān)于Java創(chuàng)建線程的2種方式以及對(duì)比的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-01-01
SpringBoot中使用Knife4j生成接口文檔的示例詳解
Knife4j 是一個(gè)基于 Swagger 的增強(qiáng) UI 實(shí)現(xiàn),主要用于為 Spring Boot 應(yīng)用程序生成 API 接口文檔,本文將詳細(xì)介紹如何在 Spring Boot 中集成 Knife4j,并通過不同注解來生成清晰的接口文檔,需要的可以參考一下2025-06-06
使用eclipse打包Maven項(xiàng)目的實(shí)現(xiàn)步驟
本文主要介紹了使用eclipse打包Maven項(xiàng)目的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03
跟我學(xué)Java Swing之游戲設(shè)計(jì)(2)
跟我學(xué)Java Swing之游戲設(shè)計(jì)(2)...2006-12-12
Spring?Boot開發(fā)時(shí)Java對(duì)象和Json對(duì)象之間的轉(zhuǎn)換
在Spring?Boot開發(fā)中,我們經(jīng)常需要處理Java對(duì)象和Json對(duì)象之間的轉(zhuǎn)換,本文將介紹如何在Spring?Boot項(xiàng)目中實(shí)現(xiàn)Java對(duì)象和Json對(duì)象之間的轉(zhuǎn)換,感興趣的朋友跟隨小編一起看看吧2023-09-09

