mybatis實現(xiàn)批量插入并返回主鍵(xml和注解兩種方法)
mybatis批量插入并返回主鍵(xml和注解兩種方法)
mybatis批量插入
在mysql數(shù)據(jù)庫中支持批量插入,所以只要配置useGeneratedKeys和keyProperty就可以批量插入并返回主鍵了。
比如有個表camera,里面有cameraNo,chanIndex,cameraName這三個字段,其中cameraNo是自增主鍵。
下面是批量插入的Dao層接口:
void batchInsertCameras(@Param("list") List<Camera> cameras);
xml形式
<insert id="batchInsertCameras" useGeneratedKeys="true" keyProperty="cameraNo">
insert into camera (chanIndex,cameraName)
values
<foreach collection="list" item="c" separator=",">
(#{c.chanIndex},#{c.cameraName})
</foreach>
</insert>
注解形式
@Insert("<script>insert into camera (chanIndex,cameraName) values " +
"<foreach collection='list' item='c' separator=','>(#{c.chanIndex},#{c.cameraName})</foreach></script>")
@Options(useGeneratedKeys = true, keyProperty = "cameraNo")
void batchInsertCameras(@Param("list") List<Camera> cameras);
注意:@Param里必須寫成list, foreach的collection也必須寫成list,否則批量插入后會報錯說找不到"cameraNo"字段,而無法返回主鍵。
通過上面的xml形式或者注解形式的配置(我這是spring boot的項目,引入的mybatis-spring-boot-starter,采用的是注解形式),就可以批量插入并返回主鍵了,主鍵會被設置到Camera對象的cameraNo字段中。
cameraMapper.batchInsertCameras(cameras);
for(Camera camera : cameras){
System.out.println(camera.getCameraNo());
}

執(zhí)行批量插入時,需確保至少有一條待插入的記錄,否則會導致sql有誤而報錯。
mybatis批量插入并返回主鍵筆記
mapper中的代碼
int insertBatchUserReturnId(List<User> users);
也可以在形參前面加上@Param("xxxx")
xml中的代碼,collection必須填list類型
<insert id="insertBatchUserReturnId" keyProperty="userId" useGeneratedKeys="true">
insert into message (user_id, user_name, user_type, user_passwd, user_phone,user_pic,user_address)
values
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item.userId,jdbcType=INTEGER}, #{item.userName,jdbcType=VARCHAR}, #{item.userType,jdbcType=TINYINT},
#{item.userPasswd,jdbcType=VARCHAR}, #{item.userPhone,jdbcType=VARCHAR},
#{item.userPic,jdbcType=VARCHAR},#{item.userAddress,jdbcType=VARCHAR}
</foreach>
</insert>
執(zhí)行完這條語句之后,原來的users就會自動帶上主鍵userId。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
解決創(chuàng)建springboot后啟動報錯:Failed?to?bind?properties?under‘spri
在Spring?Boot項目中,application.properties和application.yml是用于配置參數(shù)的兩種文件格式,properties格式簡潔但不支持層次結構,而yml格式支持層次性,可讀性更好,在yml文件中,要注意細節(jié),比如冒號后面需要空格2024-10-10
springboot實現(xiàn)自動郵件發(fā)送任務詳解
這篇文章主要介紹了Springboot中的郵件任務,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2022-04-04
SpringMVC通過RESTful結構實現(xiàn)頁面數(shù)據(jù)交互
RESTFUL是一種網(wǎng)絡應用程序的設計風格和開發(fā)方式,基于HTTP,可以使用XML格式定義或JSON格式定義。RESTFUL適用于移動互聯(lián)網(wǎng)廠商作為業(yè)務接口的場景,實現(xiàn)第三方OTT調(diào)用移動網(wǎng)絡資源的功能,動作類型為新增、變更、刪除所調(diào)用資源2022-08-08

