zoukankan      html  css  js  c++  java
  • org.apache.ibatis.binding.BindingException: Mapper method 'attempted to return null from a method with a primitive return type (long).

    一、问题描述

    今天发现测试环境报出来一个数据库相关的错误 org.apache.ibatis.binding.BindingException: Mapper method 'attempted to return null from a method with a primitive return type (long).

    二、问题根源

    经过查询后发现,Mybatis 在查询id信息的时候返回类型为long ,没有留意long和Long的区别

    • Long是long的包装类,long是基本数据类型。
    • Long可以为null,但基本类型long则不可以被赋值null。

    当在数据库中查询没有查到这条记录,注意这里是根本没有这条记录,所以当然也不会返回id,对于这种情况Mybatis框架返回结果是null

    @Select("select id from user where name = #{userName} and status = 1")
    long getInitialPolicyIdByVer(@Param("userName") String name);

    用long取承接null当然是不可以的

    Long a = null;
    long b = a;

    因为会报java.lang.NullPointerException,而框架报出来的就是attempted to return null from a method with a primitive return type (long)

    三、解决方案

    • 方案一:返回类型修改为Long就可以了,并在对应的Service层做相应的判断就可以了

    public long getUserId(String userName) {
    Long userId = userMapper.getUserId(userName);
    if (userId == null) {
    return 0;
    }
    return userId;
    }
    • 方案二:对于可以查询到记录的,只是在该记录中你需要的字段是null这种情况下,除了上述方法,还可以通过修改sql来解决。

    select ifnull(id,0) from user where name = 'test' and status = 1;
    select case id when null then 0 end from user where name = 'test' and status = 1;

    但是站在专业的角度一般在设计数据库时,相关字段都会被设置为NOT NULL DEFAULT ''

  • 相关阅读:
    翻转数组
    股神
    刮刮卡兑换
    军训队列
    击鼓传花
    上台阶
    @Service空指针异常 -JUNIT测试
    insert 配置信息
    url地址重叠
    shop = mapper.readValue(shopStr, Shop.class); shop=null的问题
  • 原文地址:https://www.cnblogs.com/lingyejun/p/8991794.html
Copyright © 2011-2022 走看看