mybatis 报错:Cause: java.lang.NumberFormatException: For input string: “”
问题描述
我使用的mybatis版本是3.5.5。
使用mybatis动态SQL进行模糊查询,if条件判断时,报出数字格式错误。
//Mapper.xml源代码<select id="selectByCondition" resultMap="brandResultMap">select *from tb_brandwherestatus = #{status}<if test="companyName != null and companyName != ' '">and company_name like #{companyName}</if><if test="brandName != null and brandName != ' '">and brand_name like #{brandName}</if></select>
org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: java.lang.NumberFormatException: For input string: "%华为%"### Cause: java.lang.NumberFormatException: For input string: "%华为%"... moreat org.apache.ibatis.scripting.xmltags.DynamicSqlSource.getBoundSql(DynamicSqlSource.java:39)at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:305)at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:87)at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:147)... 32 moreProcess finished with exit code -1
原因分析:
问题的原因在于mybiatis是基于OGNL语法,在解析单引号+单字符 ‘Y’ 的解析时会默认时char类型,单引号+多字符 ‘AA’ 或者双引号+单字符 “A” 解析为String类型。
解决方案:
把单引号和双引号的位置互换即可。
<if test='companyName != null and companyName != " "'>and company_name like #{companyName}</if>