最近用mybatis进行select和update操作,因为一般只传入一个对象,却只对其中某些属性进行查询或更新,这时要写通用的sql语句,就必然涉及到多字段判断拼接。在这里做一个总结:

1. select多字段判断拼接

只传一个ArticleQuery对象,返回Article对象,常用

    <!--文章查询的sql片断,建议是以单表为单位定义查询条件,建议将常用的查询条件都写出来-->
    <sql id="query_items_where">
        <if test="name!=null and name!=''">
            and name like '%${name}%'
        </if>
        <if test="title!=null and title!=''">
            and title like '%${title}%'
        </if>
        <if test="articleId!=null">
            and article_id = #{articleId}
        </if>
    </sql>


    <select id="queryByCondition" parameterType="ArticleQuery" resultType="Article">
            <!-- 注意ORDER BY后面用的是$而不是# -->
            select * from articles
            <where>
                <include refid="query_items_where" />
            </where>
            <!-- 排序字段判断 -->
            <if test="sort!=null and sort!=''">
                ORDER BY ${sort}
            </if>
           	<! -- 排序方向判断 -->
            <if test="direction!=null and direction!=''">
                ${direction}
            </if>

    </select>

主要通过“if”对字段是否为空进行判断,其中用到了“include”把“where”中的字段判断集中起来,这样其他sql语句可以复用

2. update多字段判断拼接

    <update id="updateArticle" parameterType="Article">
        UPDATE articles SET
         view_num =(case when #{viewNum}=null then view_num else #{viewNum} end),
         comment_num=(case when #{commentNum}=null then comment_num else #{commentNum} end),
         category_id=(case when #{categoryId}=null then category_id else #{categoryId} end),
         like_num=(case when #{likeNum}=null then like_num else #{likeNum} end)

        WHERE article_id=#{articleId}

    </update>

主要就是用“case when”进行字段判断拼接。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐