MyBatis错误

说明:记录一次MyBatis错误,错误信息如下,说数字转换异常,显然,把一个字符串类型转为数字类型,肯定是不行的。

text 复制代码
2024-08-29 19:44:43.198 ERROR 24216 --- [nio-9090-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.NumberFormatException: For input string: "hezy"
### Cause: java.lang.NumberFormatException: For input string: "hezy"] with root cause

java.lang.NumberFormatException: For input string: "hezy"

场景

(前端)

(接口)

java 复制代码
    @GetMapping("/test")
    public void test() {
        User user = new User();
        user.setId(1);
        user.setUsername("hezy");
        userRepository.selectUserById(user);
    }

(Repository)

java 复制代码
    User selectUserById(@Param("user") User user);

定位到项目的动态SQL,如下,这是我本地复现的Demo,在实际的项目中,是一个查询条件字段,表示某个分组,可选"所有分组"或者"具体某个分组",当时的开发应该是和前端约定过,当值为0时表示为所有分组,所以这个字段传递可能是0,或者是具体的分组ID,因此就有了类似下面这样的判断

(动态SQL)

xml 复制代码
    <select id="selectUserById" resultType="com.hezy.pojo.User">
        SELECT * FROM i_users WHERE id = #{user.id}
        <if test="user.username != null and user.username != '' and user.username != '0'">
            and username = #{user.username}
        </if>
        <if test="user.username == '0'">
            and username = '0'
        </if>
    </select>

分析&解决

显然,这里是有隐型的类型转换,但一眼看过去,动态SQL里面的判断都是字符串,0也用单引号包起来了。无计可施之际,我想到单引号在Java中表示的是字符,而字符又能自动转为数字进行计算,如下,所以我想是不是MyBatis底层把'0'当做数字了,然后把左边的参数也尝试转为数值类型,造成了这次错误。

于是,我想到把0通过双引号包起来,这铁定就是字符串了,双引号在XML里面需要通过&quot;转义,如下:

xml 复制代码
    <select id="selectUserById" resultType="com.hezy.pojo.User">
        SELECT * FROM i_users WHERE id = #{user.id}
        <if test="user.username != null and user.username != '' and user.username != &quot;0&quot;">
            and username = #{user.username}
        </if>
        <if test="user.username == &quot;0&quot;">
            and username = '0'
        </if>
    </select>

成功了,golder~,这个问题困扰了很久

解决 :if标签里面对数值的判断,如果你想要的是判断字符串,右边的数值需要用&quot;包起来。

相关推荐
老友@2 分钟前
Kafka 全面解析
服务器·分布式·后端·kafka
Java中文社群4 分钟前
超实用!Prompt程序员使用指南,大模型各角色代码实战案例分享
后端·aigc
风象南23 分钟前
Spring Boot 实现文件秒传功能
java·spring boot·后端
橘猫云计算机设计24 分钟前
基于django优秀少儿图书推荐网(源码+lw+部署文档+讲解),源码可白嫖!
java·spring boot·后端·python·小程序·django·毕业设计
黑猫Teng28 分钟前
Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现与实战指南
java·spring boot·后端
小智疯狂敲代码29 分钟前
Java架构师成长之路-框架源码系列-整体认识Spring体系结构(1)
后端
星河浪人34 分钟前
Spring Boot启动流程及源码实现深度解析
java·spring boot·后端
佩奇的技术笔记35 分钟前
中级:Maven面试题精讲
java·面试·maven
Lizhihao_1 小时前
JAVA-堆 和 堆排序
java·开发语言
极客先躯1 小时前
高级java每日一道面试题-2025年3月21日-微服务篇[Nacos篇]-什么是Nacos?
java·开发语言·微服务