How to avoid duplication of data when inserting in MySql batch

How to avoid duplication of data when inserting in MySql batch

Preface

Mysql inserts non-duplicate data. When a large amount of data needs to be inserted, it is necessary to determine whether the insertion is repeated and then insert it. So how to improve efficiency? There are many ways to solve the problem, and the solutions are different for different scenarios. When the amount of data is small, any solution is fine, but when the amount of data is large, it is not a simple problem.

1. insert ignore into

The data that already exists in the database will be ignored. If there is no data in the database, new data will be inserted. If there is data, the currently inserted data will be skipped. In this way, the existing data in the database can be retained, achieving the purpose of inserting data in the gap.

Controller method:

/**
 *Insert employee data*/
@PostMapping("save")
@ResponseBody
public CommonResult<Employee> save(@RequestBody Employee employee) {
    return employeeService.saveEmp(employee);
}
INSERT INTO
<!--Insert employee data-->
<insert id="saveEmp" parameterType="com.dt.springbootdemo.entity.Employee">
    INSERT INTO t_employee(id, name, age, salary, department_id)
    VALUES (#{id},#{name},#{age},#{salary},#{departmentId})
</insert> 

insert image description here

We add a new employee record with primary key ID 1.

When I send the request again, an SQL statement execution error will be reported because the primary key is unique and the record with ID=1 already exists.

insert image description here

Add ignore and add another employee record with ID=1

INSERT IGNORE INTO 

insert image description here

There was no error, but the addition was not successful, and the addition of duplicate data was ignored.

2. on duplicate key update

When the primary key or unique key is repeated, an update statement is executed.

 ON DUPLICATE KEY UPDATE id = id

We still insert the employee record with ID=1 and modify other fields (age=25):

insert image description here

View database records:

insert image description here

You can see that there is no change, there is only one piece of data, and a successful prompt is returned.

This method has a prerequisite, that is, the constraint to be inserted must be a primary key or a unique constraint (in your business, the field that needs to be used as the only judgment should be set as a unique constraint, that is, a unique key).

Extension: This method also has the needs of other business scenarios ->>>Update other fields regularly.

We add a time field to the employee table:

private Date updateTime; 

insert image description here

Then we insert data according to the updateTime field:

<insert id="saveEmp" parameterType="com.dt.springbootdemo.entity.Employee">
    INSERT INTO t_employee(id, name, age, salary, department_id,update_time)
    VALUES (#{id},#{name},#{age},#{salary},#{departmentId},now())
    ON DUPLICATE KEY UPDATE update_time = now()
</insert>

insert image description here

insert image description here

insert image description here

What should I do if I need to update other fields (such as age) when inserting?

insert image description here
insert image description here

insert image description here

3. replace into

If there are records with the same primary or unique, delete them first. Insert new records again.

REPLACE INTO
 <!--Insert employee data-->
<insert id="saveEmp" parameterType="com.dt.springbootdemo.entity.Employee">
    REPLACE INTO t_employee(id, name, age, salary, department_id,update_time)
    VALUES (#{id},#{name},#{age},#{salary},#{departmentId},now())
</insert>

insert image description here

insert image description here

Summary: In actual development, the second method is most commonly used, which is batch addition.

<!--Insert employee data-->
<insert id="saveEmp" parameterType="java.util.List">
    INSERT INTO t_employee(id, name, age, salary, department_id,update_time)
    VALUES
    <foreach collection="list" item="item" index="index" separator=",">
        (#{item.id},#{item.name},#{item.age},#{item.salary},#{item.departmentId},now())
    </foreach>
    ON DUPLICATE KEY UPDATE id = id
</insert>

Controller:

@PostMapping("save")
@ResponseBody
public CommonResult<Employee> save(@RequestBody List<Employee> employeeList) {
    return employeeService.saveEmp(employeeList);
}

insert image description here

If the same ID exists, it will not be added repeatedly.

Summarize

In actual work, method 2 is the most commonly used method, and different methods are used according to different scenarios.

This is the end of this article about how to insert data without duplication during MySql batch insertion. For more relevant MySql non-duplicate insertion content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • MySQL uses UNIQUE to implement non-duplicate data insertion

<<:  A brief discussion on the design of Tomcat multi-layer container

>>:  Question about custom attributes of html tags

Recommend

Detailed steps to store emoji expressions in MySQL

Caused by: java.sql.SQLException: Incorrect strin...

Angular Dependency Injection Explained

Table of contents Overview 1. Dependency Injectio...

A brief discussion on value transfer between Vue components (including Vuex)

Table of contents From father to son: Son to Fath...

How to simply encapsulate axios in vue

Inject axios into Vue import axios from 'axio...

A brief discussion on MySQL select optimization solution

Table of contents Examples from real life Slow qu...

How to elegantly implement WeChat authorized login in Vue3 project

Table of contents Preface Prepare Implementation ...

The first step in getting started with MySQL database is to create a table

Create a database Right click - Create a new data...

How to use webSocket to update real-time weather in Vue

Table of contents Preface About webSocket operati...

Implementation of Nginx configuration Https security authentication

1. The difference between Http and Https HTTP: It...

MySQL 8.0.18 installation tutorial under Windows (illustration)

Download Download address: https://dev.mysql.com/...

Explanation of MySQL performance inspection through show processlist command

The show processlist command is very useful. Some...

Vue implements QR code scanning function (with style)

need: Use vue to realize QR code scanning; Plugin...