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版本
調(diào)整版本號為3.5.2
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
換了版本號后,就正常了,其它版本大家可以測試下,具體從什么版本后修復(fù)的,這個暫時沒查到
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)鍵點:foreach里的collection必須是list,不然就會報錯
四、拓展說明
關(guān)于返回主鍵ID,需要在insert標(biāo)簽中添加,useGeneratedKeys=“true” keyProperty=“id”,useGeneratedKeys和keyProperty必須配合使用,keyProperty的字段就是返回的主鍵ID
mybatis3.3.1及以上的版本,才支持批量插入返回主鍵ID
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java高效打印一個二維數(shù)組的實例(不用遞歸,不用兩個for循環(huán))
下面小編就為大家?guī)硪黄猨ava高效打印一個二維數(shù)組的實例(不用遞歸,不用兩個for循環(huán))。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03Java 如何繞過迭代器遍歷時的數(shù)據(jù)修改異常
這篇文章主要介紹了Java 繞過迭代器遍歷時的數(shù)據(jù)修改異常的方法,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下2021-02-02SpringBoot使用SensitiveWord實現(xiàn)敏感詞過濾
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何使用SensitiveWord實現(xiàn)敏感詞過濾功能,文中示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下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-08Java多維數(shù)組和Arrays類方法總結(jié)詳解
這篇文章主要介紹了Java多維數(shù)組和Arrays類方法總結(jié)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03Spring-boot結(jié)合Shrio實現(xiàn)JWT的方法
這篇文章主要介紹了Spring-boot結(jié)合Shrio實現(xiàn)JWT的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05java 通過發(fā)送json,post請求,返回json數(shù)據(jù)的方法
下面小編就為大家分享一篇java 通過發(fā)送json,post請求,返回json數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03