Mybatis insert and delete batch operations

  • 2020-05-19 04:52:12
  • OfStack

In the operation of the database, often encounter batch insert, batch delete, direct execution of SQL statement is good to do 1 point, when the use of Mybatis batch insert, batch delete will have some problems. The following section describes batch insertion and deletion using Mybatis.

1. Batch insert

Java code:


// 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 code


<!-- XML: TestMapper.XML -->
...
<!--  Ignore duplicate data  -->
<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>
<!--  Update duplicate data  -->
<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>
...

Batch insert SQL statements


insert into test_table(x, y, z) values (1, 1, 1), (2, 2, 2), (3, 3, 3)

Note: VALUE() is a function of Mysql, which can be explained by looking at the document function_values.

The main function is to get the value to be updated when the data is repeated.

2. Batch deletion

Java code:


// 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 code


<!-- 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 statement


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)

Note: the code above is x,y,z for the union primary key, where id in for the common case.


Related articles: