mybaits之动态SQL


动态sql就是根据不同的条件生成不同的sql

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

1.环境搭建

2.测试

  1.动态sql之if。if里面的关键字是test。test里面去写if的条件即可

   2.动态sql之where set:可以实现and or 或者【,】的自动优化

   choose  when otherwise

    <select id="BlogListChoose" parameterType="map" resultType="blog">
        select * from  blog
        <where>
            <choose>
                <when test="title !=null">
                    and title =#{title}
                when>
                <when test="author !=null">
                    and author=#{author}
                when>
                <otherwise >
                    and views=#{views}
                otherwise>
            choose>
        where>
    select>
  
   update blog
  
  
title=#{title},
  

  
   author=#{author},
  

  

  
   id=#{id}
  

  
    @Test
    public void selectChoose(){
        SqlSession sqlSession = MybaitsUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap Map = new HashMap();
       // Map.put("title","Mybatis");
        Map.put("author","xiaochen");
        Map.put("views",1000);
        List blogs = mapper.BlogListChoose(Map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

  3.动态sql之foreach

    动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)

    foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符

    例如一个sql,分析他 (开头,)结束,or可以看做分隔符,分隔的内容是 id=#{参数}  将多个id={参数} 放在一个list中,把这个list传给Mapper.xml