mybatis报“Invalid value for getInt()“

2023-05-16

使用mybatis遇到一个非常奇葩的问题,错误如下:

Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'name' from result set.  Cause: java.sql.SQLException: Invalid value for getInt() - 'wo'

场景

还原一下当时的情况:

public interface UserMapper {
    @Results(value = {
            @Result(property = "id", column = "id", javaType = Long.class, jdbcType = JdbcType.BIGINT),
            @Result(property = "age", column = "age", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR)
    })
    @Select("SELECT id, name, age FROM user WHERE id = #{id}")
    User selectUser(Long id);
}

@Data
@Builder
public class User {
    private Long id;
    private Integer age;
    private String name;
}

public class MapperMain {
    public static void main(String[] args) throws Exception {
        MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("root");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8");

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(UserMapper.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            System.out.println(userMapper.selectUser(1L));
        }
    }
}

数据库如下:

上面是一个很简单的例子,就是根据id选出用户的信息,运行结果如下:

User(id=1, age=2, name=3)

没有任何问题,但是我再往数据库里插入一条数据,如下:

MapperMain类中增加一行代码,如下:

System.out.println(userMapper.selectUser(2L));

运行结果如下:

User(id=1, age=2, name=3)
### Error querying database.  Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'name' from result set.  Cause: java.sql.SQLException: Invalid value for getInt() - 'lh'
……

可以看出第一条查询没有问题,第二条查询就报错了

初探

其实我的直觉告诉我,是不是因为User类里字段顺序和SQL语句里select字段的顺序不一致导致的,那就来试一下吧

改一下User类里字段的顺序:

@Data
@Builder
public class User {
    private Long id;
    private String name;
    private Integer age;
}

结果如下:

User(id=1, name=3, age=2)
User(id=2, name=lh, age=3)

果不其然,直觉还是很6的

或者改一下SQL语句里select字段的顺序:

@Data
@Builder
public class User {
    private Long id;
    private Integer age;
    private String name;
}

public interface UserMapper {
    @Results(value = {
            @Result(property = "id", column = "id", javaType = Long.class, jdbcType = JdbcType.BIGINT),
            @Result(property = "age", column = "age", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR)
    })
    @Select("SELECT id, age, name FROM user WHERE id = #{id}")
    User selectUser(Long id);
}

以我们的直觉,结果肯定也没问题,果不其然,如下:

User(id=1, age=2, name=3)
User(id=2, age=3, name=lh)

再探

其实到上一步,问题已经解决了,可以继续干活了,但是搞不懂为什么,心里总觉得不踏实。

bugdebug开始,从下面的入口开始:

追踪到如下:

可以看出User这个类是有构造函数的,而且是包含所有字段的构造函数
利用这个构造函数创建实例的时候,参数的顺序就是SQL语句选择字段的顺序,不会根据映射关系去选择
所以就出现了类型不匹配

那我们再来看一下问什么会有一个这样的构造函数产生,直觉告诉我是@Builder这个注解

一起来看一下User编译后的结果:

public class User {
    private Long id;
    private String name;
    private Integer age;

    User(final Long id, final String name, final Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public static User.UserBuilder builder() {
        return new User.UserBuilder();
    }

    public static class UserBuilder {
        private Long id;
        private String name;
        private Integer age;

        UserBuilder() {
        }

        public User.UserBuilder id(final Long id) {
            this.id = id;
            return this;
        }

        public User.UserBuilder name(final String name) {
            this.name = name;
            return this;
        }

        public User.UserBuilder age(final Integer age) {
            this.age = age;
            return this;
        }

        public User build() {
            return new User(this.id, this.name, this.age);
        }
    }
}

果然如此,UserBuilder.build()方法就是利用这个构造函数来生成的。

结局

最终解决方案就是给User类加上无参的构造函数就OK了,如下:

@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer age;
    private String name;
    private Long id;
}

字段顺序随便放,最后再执行一下:

User(age=2, name=3, id=1)
User(age=3, name=lh, id=2)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mybatis报“Invalid value for getInt()“ 的相关文章

随机推荐

  • Java异常

    目录 一 什么是异常 xff1f 二 什么是异常处理 三 Java中如何进行异常处理 1 try catah块捕获异常 xff0c 分为三种情况 2 多重catch块 3 finally块 4 声明异常 throws 5 抛出异常 thro
  • Linux系统安装mysql(rpm版)

    目录 Linux系统安装mysql xff08 rpm版 xff09 1 检测当前系统中是否安装MySQL数据库 2 将mysql安装包上传到Linux并解压 3 按照顺序安装rpm软件包 4 启动mysql 5 设置开机自启 6 查看已启
  • ffmpeg 花屏的问题

    ffmpeg 首先说明 xff0c ffmpeg并非做得毫无破绽 1 网络丢包 udp 改成tcp传输并非一定不会丢包 xff0c 这个一定要清楚 xff0c 除此之外 xff0c 如果使用udp xff0c 一定要把udp的接收缓存加得合
  • 通过使用 Byte Buddy,便捷地创建 Java Agent

    Java agent 是在另外一个 Java 应用 xff08 目标 应用 xff09 启动之前要执行的 Java 程序 xff0c 这样 agent 就有机会修改目标应用或者应用所运行的环境 在本文中 xff0c 我们将会从基础内容开始
  • Electron在windows下打linux包

    在原来打包windows包的配置的基础上做一些改动即可 参考我之前的博客 Vue cli 3 x使用electron打包配置 1 修改package json配置 xff0c 下面三个字段必填 xff0c 且author要按照下面格式填写
  • python3.7.1 提示 ModuleNotFoundError: No module named ‘_ssl‘ 模块问题 ;

    gt gt gt import ssl Traceback most recent call last File 34 lt stdin gt 34 line 1 in lt module gt File 34 usr local pyth
  • CentOS安装图形桌面GNOME

    CentOS安装图形桌面GNOME 购买了阿里云服务器 xff0c 是CentOS8系统 xff0c 一直只能通过终端命令来操作 xff0c 不太方便 xff0c 所以想要安装图形桌面 xff0c 试了两种方法 xff0c 这里记录一下尝试
  • SpringBoot启动机制(starter机制)核心原理详解

    一 前言 使用过springboot的同学应该已经知道 xff0c springboot通过默认配置了很多框架的使用方式帮我们大大简化了项目初始搭建以及开发过程 本文的目的就是一步步分析springboot的启动过程 xff0c 这次主要是
  • 解决前端做excel下载的文件打不开

    常用的excel对应得mine type类型 xff1a 1 34 application vnd ms excel 34 2 34 application vnd openxmlformats officedocument spreads
  • What do software developers age 30 and over know now that they wish they had known in their 20s?

    Here are a few thoughts I 39 d also recommend a thorough read of Joe Wezorek 39 s answer to this question Life is long I
  • 树莓派安装系统之无显示器(最新版)

    之前我写过一篇安装树莓派系统的文章 xff0c 但不太详细 xff0c 也需要显示屏 xff0c 我在网上找了大量资料 xff0c 发现镜像是旧版 xff0c 于是在我一次次的实验中总结出了以下方法 xff1a 首先 xff0c 我们先安装
  • Centos7安装新版本Vscode异常解决

    sudo rpm import https packages microsoft com keys microsoft asc sudo sh c 39 echo e 34 code nname 61 Visual Studio Code
  • Ubuntu14.04上Gitlab搭建及配置

    sudo apt get install openssh server postfix 填写mail name 下载gitlab ce 10 0 1 ce 0 amd64 deb xff1a https mirrors tuna tsing
  • sftp文件上传功能实现

    参考博客 https blog csdn net u011937566 article details 81666347 方式一 使用jsch 0 1 53 jar 0 gt 添加jsch 0 1 52 jar依赖 1 gt 创建JSch对
  • 安装IDEA出现Missing essential plugins: com.intellij (platform prefix: null)如何解决

    这里写自定义目录标题 这是一个重装IDEA新版本引发的悲剧 这是一个重装IDEA新版本引发的悲剧 如果你在重装IDEA后打不开出现以下报错 com intellij ide plugins PluginManagerCore Essenti
  • Android在getString()中添加参数

    转载 xff1a http blog chinaunix net uid 20771867 id 2990700 html 转载只是给自己留一个笔记 xff0c 向原作者致敬 Android中String一般都是定义在res string
  • ftp上传,下载,删除文件

    ftp上传 xff0c 下载 xff0c 删除文件 直接看最下面的main 方法中的代码 xff0c 复制全部代码 xff0c 输入自己的ftp路径和用户信息 package com sinosoft lis ybt bl import i
  • powershell 压缩和解压zip

    项目场景 xff1a 前端项目发布到windows环境需要需要先压缩传输后再解压 问题描述 简单的压缩和解压zip在windows下 xff0c 视窗情况下 xff0c 右键就可以实现 xff0c 但是如果是在命令下 xff0c windo
  • vscode 搜索插件报 提取扩展时出错。XHR failed

    项目场景 xff1a 有一段时间没有打开vscode的插件市场了 问题描述 今天打开vscode插件管理 xff0c 搜索插件 xff0c 报了一个错误 提取扩展时出错 XHR failed xff0c 一时看不出错误原因 原因分析 xff
  • mybatis报“Invalid value for getInt()“

    使用mybatis遇到一个非常奇葩的问题 xff0c 错误如下 xff1a Cause org apache ibatis executor result ResultMapException Error attempting to get