12、动态SQL


什么是动态SQL:就是根据不同的条件生成不同的SQL语句

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

创建一个基础工程
1、导包

2、编写配置文件(下划线驼峰自动转换)
在这里插入图片描述

<settings>
	<!--- 是否开启自动驼峰命名规则(camel case)映射 -->
   <setting name="mapUnderscoreToCamelCase" value="true"/>
   <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--注册Mapper.xml-->
<mappers>
 <mapper resource="mapper/BlogMapper.xml"/>
</mappers>

3、编写实体类

@Data
public class Blog {
    private int id;
    private String title;
    private String author;
    private Date createTime; //属性名和字段名不一致
    private int views;
}

4、编写实体类对应的的Mapper接口和Mapper.xml文件

public interface BlogMapper {
}
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chen.dao.BlogMapper">

</mapper>

5、IdUtils工具类

@SuppressWarnings("all") //抑制警告
public class IDUtil {

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

}

6、插入初始数据

  • 编写接口
//插入数据
int  addBlog(Blog blog);
  • sql配置文件
   <insert id="addBlog" parameterType="blog">
       insert into blog (id,title,author,create_time,views)
       values (#{id},#{title},#{author},#{createTime},#{views})
   </insert>
  • 初始化数据
    @Test
    public void addBlogTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        blog.setId(IdUtils.getId());
        blog.setTitle("Mybatis");
        blog.setAuthor("Chen");
        blog.setCreateTime(new Date());
        blog.setViews(9999);

        mapper.addBlog(blog);

        blog.setId(IdUtils.getId());
        blog.setTitle("Java");
        mapper.addBlog(blog);

        blog.setId(IdUtils.getId());
        blog.setTitle("Spring");
        mapper.addBlog(blog);

        blog.setId(IdUtils.getId());
        blog.setTitle("微服务");
        mapper.addBlog(blog);

        sqlSession.close();
    }

12.2、IF语句

需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查

  1. 编写接口类
//查询博客
List<Blog> queryBlogIf(Map map);**
  1. 编写SQL语句
    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from blog where
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </select>

问题:这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from user where title=#{title},但是如果title为空呢?那么查询语句为 select * from user where and author=#{author},这是错误的 SQL 语句,如何解决呢?
方法一:

    <select id="queryBlogIf" 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. 测试
    @Test
    public void queryBlogIf(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        //map.put("title","Java");
        map.put("author","chen");
        List<Blog> blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

12.3、choose(when,otherwise)

有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

  1. 编写接口类
List<Blog> queryBlogChoose(Map map);
  1. 编写SQL语句
    <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <choose>
                <when test="title != null">
                    title = #{title}
                </when>
                <when test="author != null">
                    and author = #{author}
                </when>
                <otherwise>
                    and views = #{views}
                </otherwise>
            </choose>
        </where>
    </select>
  1. 测试
    @Test
    public void queryBlogChoose(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("title","Java");
		//map.put("author","chen");
        map.put("views",9999);
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

12.4、trim(where,set)

12.4.1、where标签

12.2问题的解决方法二【推荐】

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

这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

12.4.2、set标签

  1. 编写接口类
int updateBlog(Map map);
  1. 编写SQL语句
	<!--注意set是用的逗号隔开-->
    <update id="updateBlog" parameterType="map">
        update blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id = #{id}
    </update>

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

    @Test
    public void updateBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
//        map.put("title","Java");
        map.put("author","Chen");
        map.put("id","87d408ae7752493ca3ae132ef8df828a");
        mapper.updateBlog(map);
    }

12.4.3、trim标签

trim标记是一个格式化的标记,可以自定义
语法:

        <trim prefix="" prefixOverrides="" suffix="" suffixOverrides="">

        </trim>

prefix:表示在trim标签内sql语句加上前缀xxx

prefixOverrides:表示去除第一个前缀xxx

suffix:表示在trim标签内sql语句加上后缀xxx

suffixOverrides:表示去除最后一个后缀xxx

可以完成set或者是where标记的功能:

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

12.5 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 blog
        <where>
            <include refid="if-title-author"></include>
        </where>
    </select>

注意:

  • 最好基于单表来定义SQL片段
  • 不要存在where标签

12.6 Foreach

  1. 编写接口类
//查询第1,2,3号记录的博客
List<Blog> queryBlogForeach(Map map);
  1. 编写SQL语句
    <!-- 我们现在传递一个万能的map,这个map中可以存在一个集合! -->
    <select id="queryBlogForeach" parameterType="map" resultType="blog">
        select * from blog
       <!--
    	 collection:指定输入对象中的集合属性
      	 item:每次遍历生成的对象
      	 open:开始遍历时的拼接字符串
      	 close:结束时拼接的字符串
      	 separator:遍历对象之间需要拼接的字符串
     	 select * from blog where 1=1 and (id=1 or id=2 or id=3)
 	    -->
        <where>
            <foreach collection="ids" item="id" open="(" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>
  1. 测试
    @Test
    public void queryBlogForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        List<Integer> ids = new ArrayList();
        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();
    }

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了

视频链接:https://www.bilibili.com/video/BV1NE411Q7Nx?p=25

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值