Mybatis(17) ——动态SQL之IF语句

在这里插入图片描述
在这里插入图片描述



需求

    要求:传递title就按照title查询,传递author就按照author查询,什么都不传递就都查询出来


需求分析

    我们在数据库中使用SQL语句实现上面的需求就是在传入title就加上title的where子句,传入author就加上author的子句,什么都不传就整表查询
在这里插入图片描述


代码实现

  • 接口
    package com.thhh.dao;
    
    import com.thhh.pojo.Blog;
    
    import java.util.List;
    import java.util.Map;
    
    public interface BlogMapper {
        //1、添加一条博客信息
        int addBlog(Blog blog);
    
        //2、使用IF来查询博客
        List<Blog> qureryBlogIf(Map<String,Object> map);
    }
    
    
  • mapper.xml
        <select id="qureryBlogIf" 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>
    
  • 测试
    • 传入title参数
          @Test
          public void testQureryBlogIf(){
              SqlSession sqlSession = MyBatisUtils.getSqlSession();
              BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
              Map<String,Object> map = new HashMap<String,Object>();
              map.put("title","标题3");
              List<Blog> blogList = mapper.qureryBlogIf(map);
              for (Blog blog : blogList) {
                  System.out.println(blog);
              }
              sqlSession.close();
          }
      

在这里插入图片描述

  • 传入author参数
        @Test
        public void testQureryBlogIf(){
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("author","作者2");
            List<Blog> blogList = mapper.qureryBlogIf(map);
            for (Blog blog : blogList) {
                System.out.println(blog);
            }
            sqlSession.close();
        }
    
    在这里插入图片描述
  • 不传入参数
    @Test
    public void testQureryBlogIf(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map<String,Object> map = new HashMap<String,Object>();
//        map.put("author","作者2");
        List<Blog> blogList = mapper.qureryBlogIf(map);
        for (Blog blog : blogList) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

在这里插入图片描述


小结

    ① 上面的例子就是mybatis的if标签的使用,其实可以看出和JSTL的if使用方式一样,通过使用IF语句我们就可以实现原来SMBMS中按照姓名查询数据和按照职位查询数据的功能
    ②原来手写JDBC我们需要写大量的代码来实现这个功能,现在使用mybatis的if标签就实现了SQL语句的复用和动态添加


注意
在这里插入图片描述

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值