动态SQL的IF语句

IF

1、1编写Mapper接口

//通过IF查询结果
    List<blog> getBlogIF(Map map);

1、2编写Mapper配置文件

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

1、3、1实现(没有参数)

 @Test
    public void getBlogIF(){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        blogMapper mapper = sqlSession.getMapper(blogMapper.class);
        HashMap map = new HashMap();
        List<blog> blogs = mapper.getBlogIF(map);
        for (blog blog : blogs) {
            System.out.println(blog);
        }
    }

1、3、1结果

blog(id=53c3529f9e2e47f4984b4419ccc9bf40, title=Mybatis, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=9999)
blog(id=9261447cfefd40a9b91cd8afe2a073d6, title=java, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=1000)
blog(id=2b0406a7a0994a9db38c526bf9977419, title=Spring, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=9999)
blog(id=a52e6184fd6e4968b63d405a1edbe62c, title=微服务, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=9999)

1、3、2实现(有title参数)

    @Test
    public void getBlogIF(){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        blogMapper mapper = sqlSession.getMapper(blogMapper.class);
        HashMap map = new HashMap();
        map.put("title","微服务");
        List<blog> blogs = mapper.getBlogIF(map);
        for (blog blog : blogs) {
            System.out.println(blog);
        }
    }

1、3、2 结果

blog(id=a52e6184fd6e4968b63d405a1edbe62c, title=微服务, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=9999)

1、3、3 实现(有author参数)

 @Test
    public void getBlogIF(){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        blogMapper mapper = sqlSession.getMapper(blogMapper.class);
        HashMap map = new HashMap();
        //map.put("title","微服务");
        map.put("author","小落");
        List<blog> blogs = mapper.getBlogIF(map);
        for (blog blog : blogs) {
            System.out.println(blog);
        }
    }

1、3、3结果

blog(id=53c3529f9e2e47f4984b4419ccc9bf40, title=Mybatis, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=9999)
blog(id=9261447cfefd40a9b91cd8afe2a073d6, title=java, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=1000)
blog(id=2b0406a7a0994a9db38c526bf9977419, title=Spring, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=9999)
blog(id=a52e6184fd6e4968b63d405a1edbe62c, title=微服务, author=小落, createTime=Wed Jan 26 15:45:58 CST 2022, views=9999)
posted @ 2022-01-26 16:26  小罗要有出息  阅读(479)  评论(0编辑  收藏  举报