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

  • 相关阅读:
    poj3252Round Numbers
    poj2282The Counting Problem(组合)
    POJ1150he Last Non-zero Digit(组合)
    poj1715Hexadecimal Numbers(数位dp)
    Codeforces Beta Round #98 (Div. 2)(A-E)
    mysql被收购 用mariadb (转)
    vsftpd配置 (转)
    Linux文件目录结构详解 (转)
    Linux创建ftp并设置权限以及忘记ftp帐号(密码)修改 (转)
    Linux环境Nginx安装、调试以及PHP安装(转)
  • 原文地址:https://www.cnblogs.com/wkrbky/p/5877480.html
Copyright © 2011-2022 走看看