使用MyBatis查询int类型字段,返回NULL值时报异常的解决方法

当配置mybatis返回int类型时

select id="getUserIdByName" parameterType="string" resultType="int">
    SELECT
    	  id
    FROM user
    WHERE userName = #{userName}
  </select>

会报错如下:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Mapper method 'com.bill.springMybatis.dao.UserDao.getUserIdByName attempted to return null from a method with
a primitive return type (int).
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

解决方案,返回类型设置为封装类型Integer而不是基本类型int

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.bill.springMybatis.dao.UserDao">

  <cache />
  <select id="getUserIdByName" parameterType="string" resultType="Integer">
    SELECT
    	  id
    FROM user
    WHERE userName = #{userName}
  </select>
  
</mapper>

service层如果需要int数据类型,可以自动从Integer进行转换, 当然有可能加入一些判断,比如Integer为Null,赋给int可以先转成0

工程源码:

http://download.csdn.net/detail/sundongsdu/5851343

原文地址:https://www.cnblogs.com/wkrbky/p/5877480.html