首页 > 其他分享 >mybatis XML 使用 case when 代替多个if

mybatis XML 使用 case when 代替多个if

时间:2022-11-16 13:22:08浏览次数:38  
标签:XML case like title author when featured name

不建议使用

<select id="findActiveBlogLike"
        resultType="Blog">
    SELECT * FROM BLOG WHERE state = ‘ACTIVE’
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
    <if test="title == null and author == null">
        AND featured = 1
    </if>
</select>

建议使用

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

使用choose when 减少判断次数

标签:XML,case,like,title,author,when,featured,name
From: https://www.cnblogs.com/chengchenc88/p/16895560.html

相关文章