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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM