問題
使用mybatis進行批量插入的時候,並且數據庫設置的是主鍵遞增,並且在插入的時候需要返回主鍵id的時候,報null錯誤。也就是查詢不到剛剛插入到數據庫的id。
背景:
springboot+mbatis+插件spring-boot-mybatis-rw
關於插件spring-boot-mybatis-rw 是做什麼的,請見博客https://blog.csdn.net/lifen0908/article/details/102897422
解決方案
批量插入代碼
int batchInsert(@Param("records") List<BatchConf> list);
<insert id="batchInsert" useGeneratedKeys="true" keyProperty="id" parameterType="java.util.List">
insert into batch_conf (
url,
title,
keywords,
create_time,
update_time)
values
<foreach collection="records" item="record" separator=",">
(
#{record.url,jdbcType=VARCHAR},
#{record.title,jdbcType=VARCHAR},
#{record.keywords,jdbcType=VARCHAR},
#{record.createTime,jdbcType=TIMESTAMP},
#{record.updateTime,jdbcType=TIMESTAMP})
</foreach>
</insert>
在mybatis中,假如沒有插件spring-boot-mybatis-rw ,那麼按照上面的寫法,在xml中加入了useGeneratedKeys=“true” keyProperty=“id” 是可以返回主鍵了。但是加入了插件,就變成了插入數據到主庫,但是查詢主鍵id是在從庫,導致在從庫中查詢不出來id。
不能改變項目的結構,那麼就改成思路。
-
批量返回不了主鍵id,那就單條的進行插入,然後彙總得到主鍵ids。
-
先不加useGeneratedKeys=“true” keyProperty=“id”。也就是直接批量插入數據庫,然後根據是插入了數據庫的n條,再從數據庫中查詢id爲前n的id的記錄。這樣直接分開寫了,由一個批量插入變成了批量插入+查詢前n條剛剛插入的數據的ids。