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 <> '' </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:248) at org.apache.ibatis.ognl.OgnlOps.compareWithConversion(OgnlOps.java:137) at org.apache.ibatis.ognl.OgnlOps.isEqual(OgnlOps.java:178) at org.apache.ibatis.ognl.OgnlOps.equal(OgnlOps.java:548) at org.apache.ibatis.ognl.ASTEq.getValueBody(ASTEq.java:49) at org.apache.ibatis.ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:175) at org.apache.ibatis.ognl.SimpleNode.getValue(SimpleNode.java:213) at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:314) at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:394) at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:435) at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:414) at org.apache.ibatis.builder.xml.dynamic.ExpressionEvaluator.evaluateBoolean(ExpressionEvaluator.java:17) at org.apache.ibatis.builder.xml.dynamic.IfSqlNode.apply(IfSqlNode.java:15) at org.apache.ibatis.builder.xml.dynamic.MixedSqlNode.apply(MixedSqlNode.java:14) at org.apache.ibatis.builder.xml.dynamic.DynamicSqlSource.getBoundSql(DynamicSqlSource.java:22) at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:198) at org.apache.ibatis.executor.BaseExecutor.createCacheKey(BaseExecutor.java:115) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:90) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:72) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:75)
解决方案:
1.改为:test="param eq 'A'.toString()"
2.原因是OGNL语法的问题:
这里 'A' 将被认为是 char 类型,但是 'AA' 或者 "A" 将被作为 String类型。
所以我们可以用转义:<if test="name == "A"">
3.或者将 <if test="index == 'A'"> 改为 <if test='index == "A"'>。