• mybatis(九)动态SQL


    mybatis(九)动态SQL

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

    9.2测试环境

    • 编写db.properties

    • 编写 mybatis-config.xml

    • 编写 工具类

    • 编写 实体类

    • 编写 BlogMapper 接口

      List<Blog08> queryAllBlogs();
      
    • 编写 BlogMapper.xml 配置文件

      <select id="queryAllBlogs" resultType="com.qlx.pojo08.Blog08">
          select *
          from mybatis.blog b
      </select>
      
    • 测试

      • public class demo {
            SqlSession sqlSession = MybatisUtils08.getSqlSession();
            BlogMapper08 mapper = sqlSession.getMapper(BlogMapper08.class);
        
            @Test
            public void testQueryAllBlogs() {
        
                mapper.queryAllBlogs().forEach(System.out::println);
            }
        }
        
      • 结果

        image-20200924205831146

    9.3 IF

    尽量在配置加上 驼峰命名转换

    <setting name="mapUnderscoreToCamelCase" value="true"/>
    

    问题: 查询所有的博客 如果传入 要查询的作者 就把 这个作者对应的博客查询出来,如果没有传入 作者 就把所有的博客查询出来.

    9.3.1接口

    /**
     * 有条件的查询
     *
     * @param map
     * @return java.util.List<com.qlx.pojo08.Blog08>
     * @author 小小的梦想丶
     * @date 2020/09/24 21:05:57
     */
    List<Blog08> queryAllBlogs2(Map<String, String> map);
    

    9.3.2 编写xml配置文件

    <!--要求  根据传入的 作者 查询出来相应的信息
        如果没有传递  则查询所有的信息
    	其中 1=1  只是为了先让where  不报错
        -->
        <select id="queryAllBlogs2" resultType="com.qlx.pojo08.Blog08" parameterType="map">
            select *
            from mybatis.blog b
            where 1 = 1
            <if test="author !=null ">
                and author=#{author}
            </if>
        </select>
    

    9.3.3测试

    @Test
    public void testQueryAllBlogs2() {
        //  传递   作者名字
        HashMap<String, String> map = new HashMap<>();
        map.put("author", "1");
        mapper.queryAllBlogs2(map);
    }
    

    结果:

    image-20200924211956236

    @Test
        public void testQueryAllBlogs2() {
            //不传入 作者的名字
            HashMap<String, String> map = new HashMap<>(); 
            mapper.queryAllBlogs2(map);
        }
    

    结果:

    image-20200924212115600

    9.4choose、when、otherwise

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

    还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员挑选的 Blog)。

    <select id="findActiveBlogLike"
         resultType="Blog">
      SELECT * FROM BLOG WHERE state = ‘ACTIVE’
      <choose>
        <when test="title != null">
          AND title like #{title}
        </when>
        <when test="author != null and author.name != null">
          AND author_name like #{author.name}
        </when>
        <otherwise>
          AND featured = 1
        </otherwise>
      </choose>
    

    9.5trim、where、set

    前面几个例子已经合宜地解决了一个臭名昭著的动态 SQL 问题。现在回到之前的 “if” 示例,这次我们将 “state = ‘ACTIVE’” 设置成动态条件,看看会发生什么。

    <select id="findActiveBlogLike"
         resultType="Blog">
      SELECT * FROM BLOG
      WHERE
      <if test="state != null">
        state = #{state}
      </if>
      <if test="title != null">
        AND title like #{title}
      </if>
      <if test="author != null and author.name != null">
        AND author_name like #{author.name}
      </if>
    </select>
    

    如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:

    SELECT * FROM BLOG
    WHERE
    

    这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:

    SELECT * FROM BLOG
    WHERE
    AND title like ‘someTitle’
    

    这个查询也会失败。这个问题不能简单地用条件元素来解决。这个问题是如此的难以解决,以至于解决过的人不会再想碰到这种问题。

    MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:

    <select id="findActiveBlogLike"
         resultType="Blog">
      SELECT * FROM BLOG
      <where>
        <if test="state != null">
             state = #{state}
        </if>
        <if test="title != null">
            AND title like #{title}
        </if>
        <if test="author != null and author.name != null">
            AND author_name like #{author.name}
        </if>
      </where>
    </select>
    

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

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

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

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

    用于动态更新语句的类似解决方案叫做 setset 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:

    <update id="updateAuthorIfNecessary">
      update Author
        <set>
          <if test="username != null">username=#{username},</if>
          <if test="password != null">password=#{password},</if>
          <if test="email != null">email=#{email},</if>
          <if test="bio != null">bio=#{bio}</if>
        </set>
      where id=#{id}
    </update>
    

    这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)

    来看看与 set 元素等价的自定义 trim 元素吧:

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

    9.6 foreach

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

    <select id="selectPostIn" resultType="domain.blog.Post">
      SELECT *
      FROM POST P
      WHERE ID in
      <foreach item="item" index="index" collection="list"
          open="(" separator="," close=")">
            #{item}
      </foreach>
    </select>
    

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

    提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

  • 相关阅读:
    蓝凌OA 后台URL跳转(鸡肋0day)
    蓝凌后台注入分析
    蓝凌ssrf+xmldecoder
    shiro550反序列化复现
    BCEL ClassLoader加载字节码
    TemplatesImple链加载字节码
    ysoserial Commons Collections3反序列化研究
    Xstream远程代码执行(CVE-2020-26217)复现分析
    Java安全之命令执行(二)
    Java安全之命令执行(一)
  • 原文地址:https://www.cnblogs.com/lxsfve/p/13726923.html
Copyright © 2020-2023  润新知