日常開發中,做更新操作的時候的處理方法為:當這個字段有值則更新,沒有值就不更新,在mybatis的xml中表現為:
<!-- 修改記錄,只修改只不為空的字段 --> <update id="updateBySelective" parameterType="Object" > update tb_mj_user set <trim suffixOverrides="," > <if test="sort!= null" > sort=#{sort}, </if> <if test="updateBy != null" > update_by=#{updateBy}, </if> <if test="updateDate != null" > update_date=#{updateDate}, </if> <if test="delFlag != null" > del_flag = #{delFlag}, </if> </trim> where id = #{id} </update>
當sort字段為int類型的時候,我們做更新操作即使沒有給sort設值,執行完updateBySelective操作后,sort也更新為0了。
原因是:int是java的提供8中原始數據類型之一,默認值為0,無法表達未賦值的情況。此時我們可以定義sort為Integer類型,Integer默認null,可以區分未賦值的情況,也滿足updateBySelective操作的限制,不為空的時候則更新。