Mybatis批量插入,返回主鍵ID不成功,巨坑記錄
一、場景說明
批量插入,返回主鍵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)后,就正常了,其它版本大家可以測試下,具體從什么版本后修復(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)文章
java高效打印一個(gè)二維數(shù)組的實(shí)例(不用遞歸,不用兩個(gè)for循環(huán))
下面小編就為大家?guī)硪黄猨ava高效打印一個(gè)二維數(shù)組的實(shí)例(不用遞歸,不用兩個(gè)for循環(huán))。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-03-03
Java 如何繞過迭代器遍歷時(shí)的數(shù)據(jù)修改異常
這篇文章主要介紹了Java 繞過迭代器遍歷時(shí)的數(shù)據(jù)修改異常的方法,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下2021-02-02
SpringBoot使用SensitiveWord實(shí)現(xiàn)敏感詞過濾
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何使用SensitiveWord實(shí)現(xiàn)敏感詞過濾功能,文中示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-01-01
啟動(dòng) Eclipse 彈出 Failed to load the JNI shared library jvm.dll
這篇文章主要介紹了有時(shí)候,新電腦上回碰到打開Eclipse時(shí),彈出提示“Failed to load the JNI shared library jvm.dll”錯(cuò)誤,這里給大家分享解決方案2016-08-08
Java多維數(shù)組和Arrays類方法總結(jié)詳解
這篇文章主要介紹了Java多維數(shù)組和Arrays類方法總結(jié)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
Spring-boot結(jié)合Shrio實(shí)現(xiàn)JWT的方法
這篇文章主要介紹了Spring-boot結(jié)合Shrio實(shí)現(xiàn)JWT的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05
java 通過發(fā)送json,post請(qǐng)求,返回json數(shù)據(jù)的方法
下面小編就為大家分享一篇java 通過發(fā)送json,post請(qǐng)求,返回json數(shù)據(jù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03

