MyBatis更新查询中的多余逗号

MyBatis更新查询中的多余逗号

本文介绍了MyBatis更新查询中的多余逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Mybatis xml映射器文件中,我尝试编写User表的更新查询,如下所示.每个输入参数都可以为null,并且仅在不为null时更新.您不知道哪个如果"条件可能会遇到,哪个可能成为最后一个条件,因此必须在每个语句中添加逗号.

In the Mybatis xml mapper file, I tried to write update query for User table as shown below. Each of the input parameter could be null and I only update when it isn't null. You don't know which 'if' condition could fall through and which one could be the last one, thus comma has to be added in each statement.

问题是多余的','导致查询异常.看来Mybatis并没有忽略多余的逗号.

The problem is that the extra ',' causes query exception. It seems Mybatis doesn't ignore extra comma.

我的解决方法是在末尾加上"id =#{id}",但这是多余的.

My workaround is to put "id = #{id}" at the end which fixed the problem but it is redundant.

真正的解决方案是什么?

What is the real solution?

代码:

<update id="update" parameterType="User">
    UPDATE user SET

    <if test="username != null">
        username = #{username},
    </if>
    <if test="password != null">
        password = #{password},
    </if>
    <if test="email != null">
        email = #{email},
    </if>
    id= #{id} // this is redundant

    WHERE id = #{id}
</update>

PS:我使用的环境是:Java Spring + MyBatis + MySQL.

PS: The environment I am using is: Java Spring + MyBatis + MySQL.

推荐答案

感谢 MyBatis Generator '的mapper.xml文件中,我已经学会了如何抑制逗号. MyBatis的标签<set>会删除最后一个逗号.它也是用 MyBatis-动态Sql :

Thanks to MyBatis Generator's mapper.xml files, I've learnt how to suppress the commas. MyBatis has a tag <set> that erases the last comma. It's also written in MyBatis - Dynamic Sql:

您可以将其编写为:

<update id="update" parameterType="User">
    UPDATE user
    <set>
        <if test="username != null">
            username = #{username},
        </if>
        <if test="password != null">
            password = #{password},
        </if>
        <if test="email != null">
            email = #{email},
        </if>
    </set>
    WHERE id = #{id}
</update>

这篇关于MyBatis更新查询中的多余逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:22