Mybatis避免出现语法错

在使用MyBatis的时候,可能会看起来没有问题,但是代码运行的时候出现意想不到的错误。

看如下代码:

<update id="updateByPrimaryKeySelective" parameterType="com.weimob.mengdian.promotion.dao.model.PromotionInfo">
    update promotion_info set
    <if test="title != null and title!=''">
        title = #{title},
    </if>
    <if test="startTime != null and startTime!=''">
        start_time = #{startTime},
    </if>
    <if test="endTime != null and endTime!=''">
        end_time = #{endTime},
    </if>
    <if test="promotionType != null and promotionType!=''">
        promotion_type = #{promotionType}
    </if>
</update>

如上代码看起来没有什么问题,但是大家想想,如果当endTime不为空,而promotionType为空时,会有什么结果?

就会多出来一个逗号,所以代码运行的时候会出现语法错。

解决办法:

最后一个更新的字段一定要保证不是空。

posted @ 2017-08-21 16:49  alittlecomputer  阅读(365)  评论(0编辑  收藏  举报