Mybatis 插入和刪除批處理操作
在操作數(shù)據(jù)庫時,經(jīng)常會碰到批量插入、批量刪除的情況,直接執(zhí)行SQL語句還好做一點(diǎn),當(dāng)使用Mybatis進(jìn)行批量插入、批量刪除時會有一些問題。下面對使用Mybatis批量插入,批量刪除進(jìn)行介紹。
1. 批量插入
Java代碼:
// Model: Test.java @Data public class Test { private String x; private String y; private String z; } // Mapper: TestMapper.java public void insertTestList(List<Test> testList);
XML代碼
<!-- XML: TestMapper.XML --> ... <!-- 忽略重復(fù)數(shù)據(jù) --> <insert id="insertTestList" parameterType="Test"> INSERT IGNORE INTO test_table(test_x, test_y, test_z) VALUES <foreach item="item" index="index" collection="list" open="(" close=")" separator=","> #{item}.x, #{item.y}, #{item}.z </foreach> </insert> <!-- 更新重復(fù)數(shù)據(jù) --> <insert id="insertTestList" parameterType="Test"> INSERT INTO test_table(test_x, test_y, test_z) VALUES <foreach item="item" index="index" collection="list" open="(" close=")" separator=","> #{item}.x, #{item.y}, #{item}.z </foreach> ON DUPLICATE KEY UPDATE test_x = VALUES(test_x), test_y = VALUES(test_y), test_z = VALUES(test_z) </insert> ...
批量插入SQL語句
insert into test_table(x, y, z) values (1, 1, 1), (2, 2, 2), (3, 3, 3)
備注:VALUE()是Mysql的一個函數(shù),具體解釋可以查看文檔function_values。
主要功能就是在數(shù)據(jù)重復(fù)時可以獲取要更新的值。
2. 批量刪除
Java代碼:
// Model: Test.java @Data public class Test { private String x; private String y; private String z; } // Mapper: TestMapper.java public void deleteTestList(List<Test> testList);
XML代碼
<!-- XML: TestMapper.XML --> ... <delete id="deleteTestList" parameterType="Test"> DELETE FROM test_table WHERE <foreach item="item" index="index" collection="list" open="(" close=")" separator="OR"> test_x = #{item.x} AND test_y = #{item.y} AND test_z = #{item.z} </foreach> </delete> ...
SQL語句
delete from test_table where (test_x = 1 AND test_y = 1 AND test_z = 1) or (test_x = 2 AND test_y = 2 AND test_z = 2) or (test_x = 3 AND test_y = 3 AND test_z = 3)
備注:上面的代碼為x,y,z為聯(lián)合主鍵的情況,普通情況使用where id in。
以上所述是小編給大家介紹的Mybatis 插入和刪除批處理操作,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
SpringSecurity實(shí)現(xiàn)權(quán)限認(rèn)證與授權(quán)的使用示例
本文主要介紹了SpringSecurity實(shí)現(xiàn)權(quán)限認(rèn)證與授權(quán)的使用示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11使用@SpringBootTest注解進(jìn)行單元測試
這篇文章主要介紹了使用@SpringBootTest注解進(jìn)行單元測試,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09springcloud gateway網(wǎng)關(guān)服務(wù)啟動報錯的解決
這篇文章主要介紹了springcloud gateway網(wǎng)關(guān)服務(wù)啟動報錯的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03