Mybatis--动态SQL之Where语句

前面写的动态SQL–If语句

    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from mybatis.blog where 1=1
        <if test="title != null">
            and title = #{title}
        if>
        <if test="author != null">
            and author = #{author}
        if>
    select>

上面的 where 1=1 纯属就是为了拼接SQL语句而加上的,这样好吗,这样不好~~

1. Mybatis–动态SQL之Where语句

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除,说白了就是Mybatis帮我们智能的拼接SQL语句


1.1 添加Where语句的代码

    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from mybatis.blog
        <where>
            <if test="title != null">
                title = #{title}
            if>
            <if test="author != null">
                and author = #{author}
            if>
        where>
    select>

1.2 测试

    @org.junit.Test
    public void test01() {
     
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap();
        map.put("author", "天天天");
        List<Blog> blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
     
            System.out.println(blog);
        }
    }

运行结果:
Mybatis--动态SQL之Where语句_第1张图片

    @org.junit.Test
    public void test01() {
     
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap();
        map.put("title", "微服务");
        List<Blog> blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
     
            System.out.println(blog);
        }
    }

Mybatis--动态SQL之Where语句_第2张图片



你可能感兴趣的:(Mybatis,sql,java,mybatis,mysql,数据库)