报错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();
}

猜你喜欢

转载自blog.csdn.net/KeepLearnZhangXiaoBo/article/details/117750516