org.apache.ibatis.binding.BindingException: Mapper method 'attempted to return null from a method with a primitive return type (long).

1. Problem description

Today, I found that the test environment reported a database-related error

org.apache.ibatis.binding.BindingException: Mapper method 'attempted to return null from a method with a primitive return type (long).

2. The root cause of the problem

After the query, it was found that Mybatis returned the type of long when querying the id information, and did not pay attention to the difference between long and Long .

When the record is not found in the database query, note that there is no record here, so of course the id will not be returned. In this case, the Mybatis framework returns null

@Select("select id from user where name = #{userName} and status = 1")
long getInitialPolicyIdByVer(@Param("userName") String name);

Of course, it is not possible to use long to take null

Long a = null;
long b = a;

Because java.lang.NullPointerException will be reported, and what the framework reports is attempted to return null from a method with a primitive return type (long)

3. Solutions

  • Option One:

We can change the return type to Long , and make corresponding judgments in the corresponding Service layer.

public long getUserId(String userName) {
Long userId = userMapper.getUserId(userName);
if (userId == null) {
return 0;
}
return userId;
}
  • Option II:

But if the record can be queried, but in the case that the field you need in the record is null, in addition to the above method, it can also be solved by modifying the sql.

select ifnull(id,0) from user where name = 'test' and status = 1;
select case id when null then 0 end from user where name = 'test' and status = 1;

But from a professional point of view, when designing a database, the relevant fields will be set to NOT NULL DEFAULT ''

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325348356&siteId=291194637