学无先后,达者为师

网站首页 编程语言 正文

Mybatis中报错:attempted to return null from a method with a primitive return type (int)

作者:此方星河 更新时间: 2022-05-17 编程语言

发生缘由

  • 学习Mybatis的使用

环境

  • jdk版本:jdk-16.0.2
  • Idea版本:2021.2
  • Mybatis版本:mybatis-3.5.9
  • 电脑系统:win10

问题及补救

问题描述

其他文件就不在这里赘述了,有User类,自己抽取的SqlSessionUtils类,以及配置文件等等。
UserMapper.java

    /**
     * 插入一条用户信息
     */
    int insertUser(User user);

UserMapper.xml

    
    <select id="insertUser" resultType="user">
        insert into t_user values(null, #{username}, #{password}, #{age}, #{sex}, #{email});
    select>

创建测试类运行:

    @Test
    public void testInsertUser() {
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        int result = mapper.insertUser(new User(null, "张三", "243", 34, "男", "234@qq"));
        System.out.println(result);
    }

结果报错:

org.apache.ibatis.binding.BindingException: Mapper method 'com.linxuan.mybatis.mapper.UserMapper.insertUser attempted to return null from a method with a primitive return type (int).

解决方案

  • 网上搜索说可以将返回值给换一下,也就是方法的返回值换成Integer,这样返回NULL不会报错。
    int insertUser(User user);换成:Integer insertUser(User user);。同时mapper.insertUser(new User(null, "张三", "243", 34, "男", "234@qq"));的返回值也变成了Integer
    执行测试类之后确实没有报错,数据库里面也确实是添加了用户信息,可是返回值变成了NULL,这不合理啊!
  • 突然我想到了,咱们这个SQL语句是DML,插入语句的啊,我为什么要用select标签呢?
    修改为insert标签之后就不会报错了。

原文链接:https://blog.csdn.net/m0_51426055/article/details/124502734

栏目分类
最近更新