Mybatis插入/删除批处理

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

在操作数据库时,经常会碰到批量插入、批量删除的情况,直接执行SQL语句还好做一点,当使用Mybatis进行批量插入、批量删除时会有一些问题。下面对使用Mybatis批量插入,批量删除进行介绍。

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 testList);
  • XML代码


...


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


<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的一个函数,具体解释可以查看文档function_values。

主要功能就是在数据重复时可以获取要更新的值。

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 testList);
  • XML代码


...

"deleteTestList" parameterType="Test">
    DELETE FROM 
        test_table
    WHERE
    "item" index="index" collection="list" open="(" close=")" separator="OR">
        test_x = #{item.x} AND test_y = #{item.y} AND test_z = #{item.z}
    


...
  • 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为联合主键的情况,普通情况使用where id in

你可能感兴趣的:(Java)