MyBatis——动态SQL

109 阅读4分钟

「这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战

什么是动态SQL:

  • 动态SQL就是根据不同的条件生成不同的SQL语句
  • 动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了

在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少,主要是以下四种。

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

1、环境搭建

CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8

实体类

package com.cheng.pojo;
import lombok.Data;
import java.util.Date;

@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date create_time;
    private int views;
}

获取ID的工具类

package com.cheng.utils;

import lombok.Data;
import org.junit.Test;
import java.util.UUID;

public class IDUtils {
    public static String getID(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}

接口和Mapper.xml文件

public interface BlogMapper {
    //插入数据
    int addBlog(Blog blog);
}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.cheng.dao.BlogMapper">
    <insert id="addBlog" parameterType="blog">
        insert into mybatis.blog (id,title,author,create_time,views)
        values(#{id},#{title},#{author},#{create_time},#{views})
    </insert>
</mapper>

给表插入数据

import com.cheng.dao.BlogMapper;
import com.cheng.pojo.Blog;
import com.cheng.utils.IDUtils;
import com.cheng.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.Date;
public class MyTest {
    @Test
    public void addBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();

        blog.setId(IDUtils.getID());
        blog.setTitle("万里顾一程");
        blog.setAuthor("万里");
        blog.setCreate_time(new Date());
        blog.setViews(99999999);
        mapper.addBlog(blog);

        blog.setId(IDUtils.getID());
        blog.setTitle("万里顾二程");
        blog.setAuthor("玄默");
        blog.setCreate_time(new Date());
        blog.setViews(99999999);
        mapper.addBlog(blog);


        blog.setId(IDUtils.getID());
        blog.setTitle("万里顾三程");
        blog.setAuthor("淮书");
        blog.setCreate_time(new Date());
        blog.setViews(99999999);
        mapper.addBlog(blog);

        blog.setId(IDUtils.getID());
        blog.setTitle("万里顾四程");
        blog.setAuthor("云渐");
        blog.setCreate_time(new Date());
        blog.setViews(99999999);
        mapper.addBlog(blog);

        blog.setId(IDUtils.getID());
        blog.setTitle("万里顾五程");
        blog.setAuthor("安叙");
        blog.setCreate_time(new Date());
        blog.setViews(99999999);
        mapper.addBlog(blog);
        sqlSession.close();
    }
}

2、if

    //IF条件查询博客
    List<Blog> queryBlogIF(Map map);

通过 “title” 和 “author” 两个参数进行可选搜索

    <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>

3、trim、where、set

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。它的作用是移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号

   <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
                author = #{author}
            </if>
            where id = #{id}
        </set>
    </update>
    @Test
    public void updateBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("title","万里顾三程");
        map.put("author","云渐");
        map.put("id","d1f67c5cc46b4e5bbe27d1fe4ae48ac3");
        mapper.updateBlog(map);
        sqlSession.close();
    }

4、choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

    <select id="queryBlogChoose" resultType="Blog" parameterType="map">
         select *from mybatis.blog
        <where>
           <choose>
               <when test="title!=null">
 --只要第一个when符合,就只执行第一个       
                   title = #{title}
               </when>
               <when test="author!=null">
 --如果第一个when不符合,where会把and去掉,不会影响SQL的执行
                   and author = #{author}
               </when>
               <otherwise>
--如果前面两个when都不存在,就执行otherwise
                   and views=#{views}
               </otherwise>
           </choose>
        </where>
    </select>

5、forEach

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

    //查询第一二三号记录的博客
    List<Blog> queryBlogForEach(Map map);
    <select id="queryBlogForEach" parameterType="map" resultType="Blog">
        select * from mybatis.blog
        <where>
            <foreach collection="ids" item="id" open="(" separator="or" close=")">
                id = #{id}
            </foreach>
        </where>
    </select>
    @Test
    public void queryBlogForEach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        //ids是map里的一个集合,用来存放id
        ArrayList<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        map.put("ids",ids);

        List<Blog> blogs = mapper.queryBlogForEach(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

6、SQL片段

有的时候,我们会把一些功能的部分抽取出来,作为公用的sql片段,方便复用!

用sql标签定义SQL片段

   <sql id="if-title-author">
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>

引用SQL片段

   <select id="queryBlogIF" parameterType="map" resultType="Blog">
        select *from mybatis.blog
        <where>
            <include refid="if-title-author"></include>
        </where>
    </select>

注意事项:

  • 定义的SQL片段不能是太复杂的语句
  • SQL片段内不要存在where标签