mybatis 报错:Caused by: java.lang.NumberFormatException: For input string

时间:2020-12-08 14:44:45

mybatis的if标签之前总是使用是否为空,今天要用到字符串比较的时候遇到了困难,倒腾半天,才在一个论坛上找到解决方法。笔记一下,如下:

转自:https://code.google.com/p/mybatis/issues/detail?id=262

错误描述:

<select id="sltTreatment" resultType="com.vitaminmd.sunny.core.bo.Treatment">
select *
from treatment
where TRUE
<if test="index == 'A'">
AND ensubject IS NOT NULL AND ensubject &lt;&gt; ''
</if>
</select>

当使用的index为A时,这段便抛出一个NumberFormatExeption的异常,但是如果index为一个数值比如1时就运行正常。
错误:

Caused by: java.lang.NumberFormatException: For input string: "A"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at org.apache.ibatis.ognl.OgnlOps.doubleValue(OgnlOps.java:)
at org.apache.ibatis.ognl.OgnlOps.compareWithConversion(OgnlOps.java:)
at org.apache.ibatis.ognl.OgnlOps.isEqual(OgnlOps.java:)
at org.apache.ibatis.ognl.OgnlOps.equal(OgnlOps.java:)
at org.apache.ibatis.ognl.ASTEq.getValueBody(ASTEq.java:)
at org.apache.ibatis.ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:)
at org.apache.ibatis.ognl.SimpleNode.getValue(SimpleNode.java:)
at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:)
at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:)
at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:)
at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:)
at org.apache.ibatis.builder.xml.dynamic.ExpressionEvaluator.evaluateBoolean(ExpressionEvaluator.java:)
at org.apache.ibatis.builder.xml.dynamic.IfSqlNode.apply(IfSqlNode.java:)
at org.apache.ibatis.builder.xml.dynamic.MixedSqlNode.apply(MixedSqlNode.java:)
at org.apache.ibatis.builder.xml.dynamic.DynamicSqlSource.getBoundSql(DynamicSqlSource.java:)
at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:)
at org.apache.ibatis.executor.BaseExecutor.createCacheKey(BaseExecutor.java:)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:)

解决方案:

1.改为:test="param eq 'A'.toString()"
2.原因是OGNL语法的问题:
这里 'A' 将被认为是 char 类型,但是 'AA' 或者 "A" 将被作为 String类型。

所以我们可以用转义:<if test="name == &quot;A&quot;">
3.或者将 <if test="index == 'A'"> 改为 <if test='index == "A"'>。