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

  • 相关阅读:
    【转】Maven多模块项目构建
    【转】vue和springboot项目使用nginx配置,并配置跨域
    关于URL与URI
    C#将16位二进制转换为有符号数
    WPF中 datagird日期列格式
    记录一个困扰了我两个周的Windows网络问题
    基于企业上下级关系的组织机构体系数据模型设计
    WPF简介
    和尚挖井故事给程序员的启示!
    看八个笑话故事 悟八个人生道理
  • 原文地址:https://www.cnblogs.com/wkrbky/p/5877480.html
Copyright © 2011-2022 走看看