[Technical Application] Scenarios where the return value of mybatis database operations (insert, update, delete) is 0

I. Introduction

Recently, when reviewing the code of the project team members, I found that there are many mybatisdatabase operations ( insert、update、delete) in 返回值the code without any processing. In some business scenarios, there may be potential bugs, garbage data or data inconsistency. So today I deliberately in conclusion;

Mybatis's return to the database operation is worth understanding:
insert **Insert n records and return the number of affected rows n. ( n>=1When n is 0, the actual insertion fails)
update: Update n records and return the number of affected rows n. ( n>=0)
delete: Delete n records and return the number of affected rows n. ( n>=0)

It is easier for us to understand the situation where the return value n>0, but in what scenario mybatis operates (insert、update、deletethe database, the return value n = 0 , which is the main purpose of our summary today ;

2. Database exception handling

We often encounter abnormal situations when operating the database. We can directly capture the exception when 操作数据库connecting to conn . In this case, there is no return value, and the transaction rollback or other processing is directly performed on the captured exception. There is no big objection here;抛出的异常try{}catch(){}

When we write a stored procedure, some of the following situations may occur:

  • The inserted data violates the unique constraint, causing the insertion to fail.
  • Inserting or updating data exceeds the maximum field length, causing the operation to fail.
  • The number of rows affected by update is inconsistent with the expected results

When encountering the above various exceptions, we may need to capture them, and then we may need to roll back the current transaction.

3. The return value of insert operation is: 0

In mybatis, the return value of the insert operation is 0, and most of the operation failures are thrown in the form of exceptions, which we can capture through try{}catch(){};

For insert, we mainly introduce several 返回值operation commands that may return 0 or other operations, which are also more prone to errors.

1、insert ignore into

mysq support insert ignore into.
insert into means to insert data, the database will check the primary key (PrimaryKey), if there is a duplicate, an error will be reported;
insert ignoreit means that if the same record already exists in the database, the current new data will be ignored;

1) sql example:

INSERT IGNORE INTO tbl_user(id,NAME,age,pass_time)VALUES(9,'哈哈哈',18,11111111);

Results of the:

1 queries executed, 1 success, 0 errors, 1 warnings

查询:INSERT IGNORE INTO tbl_user(id,NAME,age,pass_time)VALUES(9,'哈哈哈',18,11111111)
0 行受到影响, 1 个警告

执行耗时   : 0.001 sec
传送时间   : 0.001 sec
总耗时      : 0.002 sec

2) mybatis example:

mapper method:

@Insert(value = "INSERT IGNORE INTO tbl_user (id,name,age,pass_time) VALUES (${user.id},'${user.name}',${user.age},${user.pass_time})")
Integer add(@Param(value = "user") User user);

Service class:

@Override
public Integer add(User user) {
    
    
  Integer insert = userMapper.add(user);
  System.out.println("insert 执行结果: "+insert);
  return insert;
}

Request:
id=9 data already exists in the database table tbl_user
Insert image description here

Results of the:

2022-12-15 19:45:17.972  INFO 14868 --- [nio-8079-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 0 ms
insert 执行结果: 0

2、replace into

replace intoIndicates inserting and replacing data. There is a PrimaryKey in the demand table, or unique索引if the data already exists in the database, replace it with new data (delete the old data first, and then insert the new data). If there is no data, the effect is the same as insert into;

replaceThe statement returns a number indicating the number of rows affected;

  • If the data already exists, the returned number is: the number of changed data rows + the number of execution data rows;
  • If the data does not exist, the return number is: the number of execution data rows;

The return value of mysql database execution is the return value of mybatis operation. For convenience, we will operate in the database next;

1) replace into example:

REPLACE INTO tbl_user(id,NAME,age,pass_time)VALUES(10,'小四',10,10000000000);
REPLACE INTO tbl_user(id,NAME,age,pass_time)VALUES(10,'小四',10,100000001000);

Results of the:

2 queries executed, 2 success, 0 errors, 0 warnings

查询:replace into tbl_user(id,name,age,pass_time)values(10,'小四',10,10000000000)
1 行受到影响

执行耗时   : 0.026 sec
传送时间   : 0 sec
总耗时      : 0.026 sec
-----------------------------------------------------------

查询:REPLACE INTO tbl_user(id,NAME,age,pass_time)VALUES(10,'小四',10,100000001000)
2 行受到影响

执行耗时   : 0.042 sec
传送时间   : 0 sec
总耗时      : 0.042 sec

2) mybatis example:

@Override
    public Integer test() {
    
    
        User user = new User();
        user.setId(10);
        user.setName("小四");
        user.setAge(10);
        user.setPass_time(10000000002L);
        Integer insert = userMapper.add2(user);
        System.out.println("insert 执行结果: "+insert);
        return insert;
    }

Results of the:

2022-12-15 20:54:08.698  INFO 17236 --- [  restartedMain] com.alibaba.druid.pool.DruidDataSource   : {
    
    dataSource-1} inited
insert 执行结果: 2

3、on duplicate key update

Concept : INSERT ... ON DUPLICATE KEY UPDATEUsed to solve repetitive problems. First determine whether the record exists, update it if it exists, and insert it if it does not exist. So the focus is on determining whether the record exists.
The criterion is that if the inserted record results in a unique index or primary key duplication, the record is considered to exist.

Whether the statement actually performs an insert or an update can be distinguished based on the number of affected rows:

  • The number of affected rows is 1, indicating that the row is inserted as a new record;
  • The number of affected rows is 2, indicating that the rows are duplicated and the original records are updated;
  • The number of affected rows is 0, indicating that the updated data is the same as the original data and has not actually been updated.

1) sql example:

INSERT INTO tbl_user(id,NAME,age,pass_time)VALUES(12,'小六',10,10000000000) ON DUPLICATE KEY UPDATE NAME=VALUES(NAME),age=VALUES(age),pass_time=VALUES(pass_time);
INSERT INTO tbl_user(id,NAME,age,pass_time)VALUES(12,'小六',11,10000000000) ON DUPLICATE KEY UPDATE NAME=VALUES(NAME),age=VALUES(age),pass_time=VALUES(pass_time);
INSERT INTO tbl_user(id,NAME,age,pass_time)VALUES(12,'小六',11,10000000000) ON DUPLICATE KEY UPDATE NAME=VALUES(NAME),age=VALUES(age),pass_time=VALUES(pass_time);

Results of the:

3 queries executed, 3 success, 0 errors, 3 warnings

查询:INSERt INTO tbl_user(id,NAME,age,pass_time)VALUES(12,'小六',10,10000000000) on duplicate key update NAME=VALUES(NAME),age=VALU...
1 行受到影响, 3 个警告

执行耗时   : 0.057 sec
传送时间   : 0.001 sec
总耗时      : 0.058 sec

注意:要查看所有警告的完整列表,请启用 工具 -> 首选项 -> 常规 -> 在信息选项卡下显示警告
-----------------------------------------------------------

查询:INSERT INTO tbl_user(id,NAME,age,pass_time)VALUES(12,'小六',11,10000000000) ON DUPLICATE KEY UPDATE NAME=VALUES(NAME),age=VALU...
2 行受到影响, 3 个警告

执行耗时   : 0.063 sec
传送时间   : 0 sec
总耗时      : 0.063 sec

注意:要查看所有警告的完整列表,请启用 工具 -> 首选项 -> 常规 -> 在信息选项卡下显示警告
-----------------------------------------------------------

查询:INSERT INTO tbl_user(id,NAME,age,pass_time)VALUES(12,'小六',11,10000000000) ON DUPLICATE KEY UPDATE NAME=VALUES(NAME),age=VALU...
0 行受到影响, 3 个警告

执行耗时   : 0.001 sec
传送时间   : 0 sec
总耗时      : 0.001 sec

注意:要查看所有警告的完整列表,请启用 工具 -> 首选项 -> 常规 -> 在信息选项卡下显示警告

2) mybatis example:

@Override
    public Integer test() {
    
    

        //  12,'小六',11,10000000000

        User user = new User();
        user.setId(15);
        user.setName("小六");
        user.setAge(11);
        user.setPass_time(10000000010L);
        Integer insert = userMapper.add3(user);
        System.out.println("insert 执行结果: "+insert);
        return insert;
    }

Results of the:

2022-12-15 21:01:41.720  INFO 12340 --- [  restartedMain] com.alibaba.druid.pool.DruidDataSource   : {
    
    dataSource-1} inited
insert 执行结果: 1

Note: When the insert data has not changed, the number of affected rows returned by the execution of the mysql client is 0, but the return value of the execution of the mybatis is 1. The reason here remains to be analyzed;

4. The return value of the update operation is: 0

updateA common situation where the return value of the operation is 0 is: when updating the data in the database table according to the primary key, if there is no data with id=13 in the database table tbl_user, the number of rows affected will be returned: 0

1) sql example:

UPDATE tbl_user SET NAME='小七' , age=18, pass_time=10000000000 WHERE ID=13

Results of the:

<n>查询:UPDATE tbl_user SET name='小七' , age=18, pass_time=10000000000 WHERE ID=13
0 行受到影响

执行耗时   : 0.001 sec
传送时间   : 0 sec
总耗时      : 0.001 sec

2) mybatis example:

@Override
    public Integer test() {
    
    

        //  12,'小六',11,10000000000

        User user = new User();
        user.setId(13);
        user.setName("小七");
        user.setAge(18);
        user.setPass_time(10000000010L);
        Integer insert = userMapper.update(user);
        System.out.println("insert 执行结果: "+insert);
        return insert;
    }

Results of the:

2022-12-15 21:04:41.245  INFO 7896 --- [  restartedMain] com.alibaba.druid.pool.DruidDataSource   : {
    
    dataSource-1} inited
insert 执行结果: 0

5. The return value of delete operation is: 0

deleteA common situation where the return value of an operation is 0 is: when deleting data in a database table based on a certain attribute (for example, id=13), if there is no data with id=13 in the database table tbl_user, the number of rows affected will be returned: 0

1) sql example:

DELETE FROM tbl_user WHERE ID = 13;

Results of the:

1 queries executed, 1 success, 0 errors, 0 warnings

查询:DELETE FROM tbl_user WHERE ID = 13
0 行受到影响

执行耗时   : 0.001 sec
传送时间   : 0.001 sec
总耗时      : 0.002 sec

2) mybatis example:

@Override
    public Integer test() {
    
    

        //  12,'小六',11,10000000000

        /*User user = new User();
        user.setId(13);
        user.setName("小七");
        user.setAge(18);
        user.setPass_time(10000000010L);*/
        Integer delete = userMapper.delete(13);
        System.out.println("insert 执行结果: "+delete);
        return delete;
    }

Results of the:

2022-12-15 21:06:17.742  INFO 12644 --- [  restartedMain] com.alibaba.druid.pool.DruidDataSource   : {
    
    dataSource-1} inited
insert 执行结果: 0

6. Summary

When using mybatis to operate the database , the return value must be combined with different usage scenarios for business processing to avoid potential bugs and also reflect the standardization of the code.

Guess you like

Origin blog.csdn.net/weixin_37598243/article/details/128334546