[Mybatis]6.动态SQL

环境搭建

1.新建表:

image

2.写实体类

image

3.初始化表:

image

<if>的使用:

现在实现需求:查询一个记录,可以没有限定,也可以限定title或者author

  • 接口中声明方法:
    List<Blog>queryBlogIF(Map map);
    使用map放参数,方便放title或者author,或者全放,或者全不放。
  • xml中添加:
<select id="queryBlogIF" parameterType="map" resultType="Blog">
 select * from mybatis1.blog
 <where>
  <if test="title != null">
   and title = #{title}
  </if>
  <if test="author != null">
   and author = #{author}
  </if>
 </where>

</select>

where标签:自动在sql中添加where、去除无关的and,or等。
set标签:自动添加set、去除无关的逗号。
(trim标签可以自定义,暂时还不懂)

  • 编写测试方法:
    @Test
    public void testIF(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("title","Java");
        List<Blog> blogs = mapper.queryBlogIF(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

查询title为Java的记录:
image


map不放参数:

    @Test
    public void testIF(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Blog> blogs = mapper.queryBlogIF(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

全部查出:
image

<choose>的使用:

choose相当于switch case,且有break。

  • 语法:
 <select id="queryBlogChoose" parameterType="map" resultType="Blog">
  select * from mybatis1.blog
  <where>
   <choose>
     <when test="title!=null">
      title=#{title}
     </when>
     <when test="author!=null">
     and author=#{author}
     </when>
    <otherwise>
     views = #{views}
    </otherwise>
   </choose>
  </where>

 </select>
  • 测试:
    @Test
    public void testChoose(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("title","Java");
        map.put("author","k狂神说");
        map.put("views",10000);
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
  • 结果
    image
    可见,choose只执行了title=#{title}。也就是break掉了。

<forech>的使用:

foreach用来实现遍历

  • 语法
 <select id="queryBlogForeach" parameterType="map" resultType="Blog">
  select * from mybatis1.blog
  <where>
      title in
   <foreach collection="titles" item="title" open="(" separator="," close=")">
     #{title}
   </foreach>
  </where>

 </select>

collection:集合的变量名。 item:变量名称 open:开头 separator:分隔符 close:结尾
上面的语句相当于: select * from mybatis1.blog where title in (xx,xx,xx,....)

posted @ 2021-11-22 16:11  从零开始学java_wxz  阅读(23)  评论(0)    收藏  举报