前言
今天在一个项目中使用Mybatis的动态查询语句,遇到如下问题:
There is no getter for property named ‘stype’ in ‘class java.lang.Integer’
起因
在做一个查询时,传的参数是个Integer类型的变量,而不是键值对式的,同时在xml中对其进行了判断。代码如下: java中 [toggle hide=“no” title=“java中” color=""]
public String findOneCode(Integer type){ return sqlSessionTemplate.selectOne("CodeObj.findOneCodeAndType",type); }[/toggle] 对应Mybatis的xml: [toggle hide=“yes” title=“对应Mybatis的出错的xml” color=""]
<select id="findOneCodeAndType" resultType="String"> SELECT code FROM code_form <where> ISNULL(uphone) <choose> <when test="stype !=null"> AND `type` = #{stype} </when> <otherwise> AND `type` = 1 </otherwise> </choose> </where> LIMIT 1; </select>[/toggle] 而当将里面的判断去掉就不在报错了,如下: [toggle hide=“yes” title=“对应Mybatis的去掉判断的xml” color=""]
<select id="findOneCodeAndType" resultType="String"> SELECT code FROM code_form <where> ISNULL(uphone) AND `type` = #{stype} </where> LIMIT 1; </select>[/toggle]
解决方案
在网上搜索答案,都说将自定义变量改为_parameter即可。按所说改后,发现果然ok了,至此分析,感觉应该是 test="stype !=null"中当为非键值对的变量时,无法获得对应变量的get,而_parameter是mybatis中默认的存放参数变量的,想了解具体的各位可去研究下其源码。 附录解决后的代码: [toggle hide=“yes” title=“对应Mybatis的不再报错的xml” color=""]
<select id="findOneCodeAndType" resultType="String"> SELECT code FROM code_form <where> ISNULL(uphone) <choose> <when test="_parameter !=null"> AND `type` = #{_parameter} </when> <otherwise> AND `type` = 1 </otherwise> </choose> </where> LIMIT 1; </select>[/toggle]

评论