zoukankan      html  css  js  c++  java
  • 使用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

  • 相关阅读:
    剑指offer(18)二叉搜索树的后续遍历
    剑指offer(17)层次遍历树
    剑指offer(16)栈的压入、弹出序列
    剑指offer(15)
    剑指offer(14)
    剑指offer(13)
    剑指offer(12)
    剑指offer(11)
    2020 年 11 月编程语言排行榜,Python 势如破竹,超越 Java?
    Python 除了 time.sleep,你还有一个暂停代码的方法
  • 原文地址:https://www.cnblogs.com/wkrbky/p/5877480.html
Copyright © 2011-2022 走看看