Mybatis 實現Mysql批量插入資料,判斷資料是否存在
阿新 • • 發佈:2019-01-27
常見插入資料的SQL
- insert into 插入資料庫時會檢查主鍵是否存在,存在會報錯
- replace into 替換資料庫記錄,需要表中有主鍵或者unique索引,如果資料庫已存在的資料,會先刪除該資料然後新增。不存在的資料效果和insert into 一樣。
<insert id="insertInfoBatch" parameterType="java.util.List">
replace into GOVRECEIPTS (state,orgname,orgaddr,regauth,rcptyear,receipts,crtdate)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.state}, #{item.orgname}, #{item.orgaddr}, #{item.regauth},
#{item.rcptyear}, #{item.receipts}, #{item.crtdate})
</foreach>
</insert>
- insert ignore 需要表中有主鍵或者unique索引,如果資料庫中存在相同的資料,則忽略當前資料。不存在的資料效果和insert into 一樣。
<insert id="insertInfoBatch" parameterType="java.util.List">
insert ignore GOVRECEIPTS (state,orgname,orgaddr,regauth,rcptyear,receipts,crtdate)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.state}, #{item.orgname}, #{item.orgaddr}, #{item.regauth},
#{item.rcptyear}, #{item.receipts}, #{item.crtdate})
</foreach>
- on duplicate key update 使用該語法可在插入記錄的時候先判斷記錄是否存在,如果不存在則插入,否則更新,很方便,無需執行兩條SQL
注意:需要設定Mysql表的unique唯一索引值