mybatisplus query specific field null pointer exception

1. Problem

An exception occurs when calling the interface. According to the log information, it is displayed as a null pointer exception. The code where the null pointer exception occurs is located in the last line of the following code return StringUtils.isNotEmpty(one.getPassword());

    public boolean isHasPwd(Long userId){
    
    
        QueryWrapper<SysUser> wrapper =Wrappers.<SysUser>query().select("password").eq("id",userId);
        final SysUser one = this.getOne(wrapper);
        return StringUtils.isNotEmpty(one.getPassword());
    }

Combining the code and the null pointer exception, it is not difficult to infer that when the one object is null, the current phenomenon can be established. A null pointer exception is reported.
The following is the SQL query log before the null pointer exception occurs:

==>  Preparing: SELECT password FROM sys_user WHERE deleted=0 AND (id = ?)
==> Parameters: 1(Long)
<==    Columns: password
<==        Row: null
<==      Total: 1

Through the log printed by SQL, we found that total is 1, which means that a piece of data can be found. Does that mean that the one object should not be null? But through verification, the result is one is null.
Insert image description here
Take a look at the database. The data with ID 1 exists, but the password field is null. What
Insert image description here
if password is an empty string:
Insert image description here
Look at the results (picture below), the object one exists, and password is an empty string; In this case, a null pointer exception will not occur.
Insert image description here
Therefore, when only querying a certain field, if the field is null, the queried entity object will be null. This must be noted.

2. Solve

When we query a specific field and use an object to receive it, we need to make a double judgment on the field used. We must not only ensure that the queried object is not null, but also ensure that the fields we need in the object are not null, otherwise we will When making a call, if the object is obviously not null, a null pointer exception error will occur.

    public boolean isHasPwd(Long userId){
    
    
        QueryWrapper<SysUser> wrapper =Wrappers.<SysUser>query().select("password").eq("id",userId);
        final SysUser one = this.getOne(wrapper);
        return ObjectUtils.isNotEmpty(one) && StringUtils.isNotEmpty(one.getPassword());
    }

Guess you like

Origin blog.csdn.net/mcband/article/details/128438865