MyBatis version
3.4.0
Database vendor and version
MySQL 5.7.29
Test case or example project
public class PersonDO {
private Long id;
private String name;
private Integer age;
// ...getter/setter
}
public interface PersonMapper {
int update(PersonDO personDO);
}
<update id="update">
update person
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="age != null and age != ''">
age = #{age},
</if>
</set>
where id = #{id}
</update>
test case:
PersonDO personDO = new PersonDO();
personDO.setId(1L);
personDO.setName("mina");
personDO.setAge(0);
personMapper.update(personDO);
Steps to reproduce
run test case
note personDO.setAge(0);
,if age's value is not zero, there will be no problem
Expected result
==> Preparing: update person SET name = ?, age = ? where id = ? ==> Parameters: mina(String), 90(Integer), 1(Long)
Actual result
==> Preparing: update person SET name = ? where id = ? ==> Parameters: mina(String), 1(Long)
the parameter age is missing
Workarounds
<if test="age != null and age != ''">
age = #{age},
</if>
can be replaced by
<if test="age != null ">
age = #{age},
</if>
because OgnlOps.equal(0, "")
will return true
but when the problem occurs, there is no hint or useful log, and the problem is obscure only when the parameter is set to zero
Comment From: harawata
Hello @wuyangLife .
The workaround is the correct way.
You don't compare Integer
with char
nor String
.