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