NumberFormatException: For input string的解决办法

时间:2025-04-11 22:45:24

提示的异常信息

: For input string: "1613989034357489665"
	at (:65) ~[na:1.8.0_333]
	at (:583) ~[na:1.8.0_333]
	at (:615) ~[na:1.8.0_333]
	at (:96) ~[classes/:na]
	at $$FastClassBySpringCGLIB$$(<generated>) ~[classes/:na]
	at (:218) ~[spring-core-5.2.:5.2.]
	at $(:685) ~[spring-aop-5.2.:5.2.]
	at $$EnhancerBySpringCGLIB$$(<generated>) ~[classes/:na]
	at (:30) ~[classes/:na]
	at .invoke0(Native Method) ~[na:1.8.0_333]
	at (:62) ~[na:1.8.0_333]
	at 

分析原因

这个异常是字符转化为int的时候出现问题了

我是做一个注册接口,需求是前端需求传过来注册的用户名和密码,要返回一个int型的id(主键)

我一开始的方案id的主键策略用的是Mybatis Plus自带的雪花算法来生成id,所以生成的id是一个19位数字的随机数,要求又要我转化为int返回,生成的是String类型的,我在转化的过程中把19位数组的字符串转化为int的时候,就出现了这个异常,因为19位数字是超过int长度的。

所以出现报错

于是我把id换成了123再进行转化,发现就没有出现这种错误了

解决方案

我把mybatis-plus的主键策略从雪花算法改成了主键自增策略,数据库id类型也从varchar改成了int型,因为前端的app是已经写好了的,他就要求我返回int型的id

最后就解决了这种问题。