[Mybatis]动态SQL之IF、trim、choose标签(重点)

166 阅读1分钟

if标签

查询接口

/**
 * 查询博客
 * @param map
 * @return
 */
List<Blog> queryBlogIf(Map map);

if标签SQL拼接(建议搭配where)

<select id="queryBlogIf" parameterType="map" resultType="com.studymb.pojo.Blog">
    select * from blog where 1=1
    <if test="title != null and title != '' and title !='null' and title !='undefine'">
        and title=#{title}
    </if>
    <if test="author != null and author != '' and author !='null' and author !='undefine'">
        and author=#{author}
    </if>
</select>

测试

@Test
public void queryBlog(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

    HashMap map = new HashMap<>();

    List<Blog> blogs = mapper.queryBlogIf(map);
    blogs.forEach(b -> {
        System.out.println(b);
    });

    sqlSession.close();
}

trim

trim之where标签

where元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where元素也会将它们去除。

<select id="queryBlogIf" parameterType="map" resultType="com.studymb.pojo.Blog">
    select * from blog
    <where>
        <if test="title != null and title != '' and title !='null' and title !='undefine'">
           title=#{title}
        </if>
        <if test="author != null and author != '' and author !='null' and author !='undefine'">
            and author=#{author}
        </if>
    </where>
</select>

trim之set标签

用于动态更新语句的类似解决方案叫做 *set*。*set* 元素可以用于动态包含需要更新的列,忽略其它不更新的列。

set元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

<update id="updateBlog" parameterType="map">
    update blog 
    <set>
        <if test="title != null and title != '' and title !='null' and title !='undefine'">
            title = #{title},
        </if>
        <if test="author != null and author != '' and author !='null' and author !='undefine'">
            author = #{author},
        </if>
    </set>
    where id = #{id}
</update>

choose(when、otherwise)

<select id="queryBlogByChoose" resultType="com.studymb.pojo.Blog" parameterType="map">
    select * from blog
    <where>
        <choose>
            <when test="title != null and title != '' and title !='null' and title !='undefine'">
                title = #{title}
            </when>
            <when test="author != null and author != '' and author !='null' and author !='undefine'">
                and author = #{author}
            </when>
            <otherwise>
                and views = # {views}
            </otherwise>
        </choose>
    </where>
</select>