用mybatis進行一個修改操作的時候,int age 我並沒沒有給它賦值,執行完成修改后發現原有的age的值修改為0,
先看看mapper.xml里面的sql
<update id="updateUser" parameterType="u">
update t_user
set
<if test="username!=null">
username=#{username},
</if>
<if test="realname!=null">
realname=#{realname},
</if>
<if test="password!=null">
password=#{password},
</if>
<if test="age!=null ">age=#{age}</if>
where userid=#{userid}
</update>
我沒有傳age值到對象當中,age是int類型 默認為0,假如age為空 我們還不想它修改原來的值得話需要在age后面添加判斷條件
先看看出錯之前的sql
<update id="updateUser" parameterType="u">
update t_user
set
<if test="username!=null">
username=#{username},
</if>
<if test="realname!=null">
realname=#{realname},
</if>
<if test="password!=null">
password=#{password},
</if>
<if test="age!=null and age!=''">age=#{age}</if>
where userid=#{userid}
</update>
運行測試程序報錯提示
報錯### Cause: java.sql.SQLException: ORA-01747: user.table.column, table.column 或列說明無效
原來沒有寫set標簽
<update id="updateUser" parameterType="u">
update t_user
<set>
<if test="username!=null">
username=#{username},
</if>
<if test="realname!=null">
realname=#{realname},
</if>
<if test="password!=null">
password=#{password},
</if>
<if test="age!=null and age!=''">age=#{age}</if>
</set>
where userid=#{userid}
</update>
這樣寫的修改成功,並且之前的值也不會修改成默認的值0
假如一個int 類型的 a 它不能為空 但是它可以為0可以這樣寫
<if test="a!=null and a!='' or a==0">
a=#{a}
</if>
補充:
我發現在有set節點包裹的if條件判斷時可以這么寫 直接判斷age!=0即可,它原來的值也不會改變。
<update id="updateUser" parameterType="u">
update t_user
<set>
<if test="username!=null">
username=#{username},
</if>
<if test="realname!=null">
realname=#{realname},
</if>
<if test="password!=null">
password=#{password},
</if>
<if test="age!=0">age=#{age}</if>
</set>
where userid=#{userid}
</update>
原創不易,如果這篇博文對你有所幫助,麻煩動動你發財的小手支持一下謝謝。