报错java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String解决踩坑

java.lang.ClassCaption: java.lang.Long cannot be cast to java.lang.String

问题背景

service传参调用mapper,报错:

[09 17:56:54,707 DEBUG] [http-nio-8081-exec-9] handler.SimpleMappingExceptionResolver - Resolving to view 'WEB-INF/500' for exception of type [java.lang.ClassCastException], based on exception mapping [java.lang.Throwable]
[09 17:56:54,707 DEBUG] [http-nio-8081-exec-9] handler.SimpleMappingExceptionResolver - Exposing Exception as model attribute 'exception'
[09 17:56:54,707 DEBUG] [http-nio-8081-exec-9] servlet.DispatcherServlet - Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'WEB-INF/500'; model is {exception=java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String}
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String

//加判断,如果已经使用,无法删除
Map<String, String> template = detectionTemplateMapper.queryTypeById(id);
//查询异常工单是否使用
if(adminOrderMapper.findCountByDetection(template.get("id").toString(),template.get("detectionType"))>0){
    return 0;
}
<select id="queryTypeById" resultType="java.util.HashMap">
    SELECT id,detectionType,ordernum,isSingle,isMainType,remark from work_detection_template where id=#{0}
</select>

问题分析

因为查询的id数据库是int类型,返回结果为Long类型,所以想着toString即可,结果还是报错,改为String.valueOf()后不报错了。

问题总结

转换字符串,尽量使用valueOf()方法吧

/**
 * Returns the string representation of the {@code Object} argument.
 *
 * @param   obj   an {@code Object}.
 * @return  if the argument is {@code null}, then a string equal to
 *          {@code "null"}; otherwise, the value of
 *          {@code obj.toString()} is returned.
 * @see     java.lang.Object#toString()
 */
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值