The return type of the query using MyBatis is int, but when the query result is NULL, the solution to the exception is reported

From http://www.cnblogs.com/zsg88/p/7746341.html

Using MyBatis to query the return type is int, but when the query result is NULL, an exception will be reported.

E.g:

  <select id="getPersonRecordId" parameterType="java.lang.String" resultType="int">
    select role_id
    from p_person_role
    where stffe_id = #{stffeId,jdbcType=VARCHAR}
  </select>

When the record does not exist, the following error will be reported

Servlet.service() for servlet [springDispatcherServlet] in context with path [/xxxx] threw exception [Request processing failed;
nested exception is org.apache.ibatis.binding.BindingException: Mapper method 'com.xxx.PersonRoleRelationMapper.getPersonRecordno attempted to return null from a method with a primitive return type (int).]
with root cause org.apache.ibatis.binding.BindingException: Mapper method 'com.xxx.PPersonRoleRelationMapper.getPersonRecordno attempted to return null from a method with a primitive return type (int).

If you encounter this problem, you can use MySQL's IFNULL function and MAX function to convert the returned NULL value to 0. For example, the above SQL statement can be changed to:

select IFFULL(MAX(role_id),0) AS role_id  from  p_person_role where  stffe_id = #{stffeId,jdbcType=VARCHAR}

 


 

In SQLSERVER we can write:
select ISNULL(max(data),0) ...


 

In Oracle we can write:
select NVL(max(data),0) ...


 

A method applicable to all databases can be written like this:
select COALESCE(max(data),0) ...


 

Of course, the above max can also be replaced by the sum function.


Guess you like

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