Dynamic SQL does not work for checking parameter is null.

20 views
Skip to first unread message

Ming Xia

unread,
Apr 26, 2019, 1:49:59 AM4/26/19
to mybatis-user
Hi,

I was trying to use mybatis dynamic sql, but seems it does not produce correct sql statement when checking if a specific parameter is null. Even `record.description==null`, the generated sql still include set description=?, and the record in db is updated with description=`null`, even it was not null before updating. Any idea on this problem, or it is a bug of MyBatis? My Mybatis version is 3.4.0.

Thanks,
Ming


@Update({
   
"<script>",
      "update city",
      "<set>",
        "<if test='#{description} != null'>description = #{description,jdbcType=VARCHAR},</if>",
      "</set>",
      "where name = #{name,jdbcType=VARCHAR}",
    "</script>"
})
@Override
int update(CityDO record);

My `CityDO` has only `name` and `description` field, and I verified that the description field is null before passing it to the `update` method.

Guy Rouillier

unread,
Apr 27, 2019, 12:26:16 AM4/27/19
to mybati...@googlegroups.com
Expressions within the tags - <if>, in this case - are Java expressions (specifically, OGNL expressions), not parameter expressions. So, the proper test here would be:

<pre>
<if test='description != null'>
description = #{description,jdbcType=VARCHAR},
</if>
</pre>

You don't have to have the entire clause on a single line, though you may if you prefer.
I think it's a little more readable to have the tags on separate lines from the text within the tags.

--
Guy Rouillier

Ming Xia

unread,
Apr 27, 2019, 7:59:51 PM4/27/19
to mybati...@googlegroups.com
Verified and it works, thank you Guy, appreciate your help.

Best,
Ming

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mybatis-user...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages