mybatis-select与update多字段判断拼接-xml写法

最近用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”进行字段判断拼接。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值