Mybatis中if标签初次使用带来的异常问题以及解决方案

问题 :

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'unitId' in 'class java.lang.Integer'...

那么什么情况下会发生“There is no getter for property named in ‘class java.lang.Integer’”错误呢?

其实是在这种情况下:

 <select id="getRiskMember" resultMap="BaseResultMap" parameterType="Integer">
    select * from Classdemo
    <where> <if test="id!= null"> and id= #{id} </if>
    </where>
</select>

注意看,是在if test=验证的时候发生的 “There is no getter for property named in ‘class java.lang.Integer’”,

而并非是and id= #{id} 的时候发生的错误。

解决方案:

1.用" _parameter "来代替。

<select id="getRiskMember" resultMap="BaseResultMap" parameterType="Integer">

    select * from Classdemo
    <where>
      <if test="_parameter != null">

        and id= #{id}
       </if>

    </where>

</select>


 2.全部的参数都换成"_parameter",

<select id="queryById" parameterType="long" resultMap="HashMap">
    SELECT * FROM <include refid="t_pt_category"/>
        <where>
            1 = 1
            <if test="_parameter != null">
                AND id = #{_parameter}
            </if>
        </where>
        ORDER BY id
</select>

3.多个参数出现的错误解决

if 标签中常见的多判断条件的错误写法: 

<if test=" takeWay == '1' and workday != null "> 

改为<if test='takeWay == "1" and workday != null '>   请注意符号 "" 即可。

或改为<if test="takeWay == '1'.toString() and workday != null "> 即可。

原因是:mybatis是用OGNL表达式来解析的,在OGNL的表达式中,’1’会被解析成字符,

而java是强类型的,char 和 一个string 会导致不等,所以if标签中的sql不会被解析。 

总结下使用方法:单个的字符要写到双引号里面,或者使用.toString()才能解决!

<select id="getExperienceMapper" resultType="HashMap" parameterType="Integer">
  select DISTINCT o.NAME, p.PLAIN_NUM, p.CURRENT_NUM

     from cpc_organization o, cpc_plan p, cpc_meeting m
    <where>
      <if test="_parameter != null">
        and m.PLAN_ID=p.ID and m.ORG_ID=o.PARENT_ID
      </if>
      <if test=' "_parameter==1" '>
        and m.END_TIME between '2018-01-01' and '2018-03-31'
      </if>
    </where>
</select>

posted @ 2018-01-10 10:26  用什么暖你一千岁!  阅读(2719)  评论(0编辑  收藏  举报