有没有mybatis' pre-interceptor'在sql执行之前以编程方式更改sql?

时间:2014-03-14 09:21:40

标签: java mysql sql mybatis

在我当前的项目中,update语句与那些非null bean属性组合在一起,我们忽略那些null bean属性以防止错误地将字段更新为null。

例如

(不是实际代码,只是帮助理解)

update person 
set
<if test=" address != null and address != '' ">
    address = #{address},
</if>
<if test=" name != null and name != '' ">
    name = #{name},
</if>
where id = #{id}

如果我们设置person.address = '--set-to-null--'person.name = 'john'person.id = 1

mybatis会生成一个sql

update person set address = '--set-to-null--', name = 'john' where id = 1;

我的问题是,我如何以编程方式将sql更改为

update person set address = null, name = 'john' where id = 1;

在mybatis执行sql之前

我希望我明白这个问题,非常感谢。

1 个答案:

答案 0 :(得分:0)

尝试绑定:

<bind name="newAddress" value = "address.equals(\"--set-to-null--\") ? org.me.Utils.defaultAddress() : address"/>
update person 
set
<if test=" address != null and address != '' ">
  address = #{newAddress},
</if>
<if test=" name != null and name != '' ">
  name = #{name},
</if>
where id = #{id}