Mybatis学习-动态SQL

本文介绍了如何在Mybatis 3中使用动态SQL技术,包括IF、CHOOSE、TRIM、WHEN和FOREACH,展示了如何根据条件动态构建SQL查询。通过实例演示了如何使用IF和WHEN元素进行条件过滤,以及如何利用TRIM和FOREACH简化复杂查询。
摘要由CSDN通过智能技术生成

Mybatis学习-动态SQL

什么是动态SQL

动态SQL就是根据不同的条件生成不同的sql语句
动态SQL和 JSTL 或任何基于类 XML 语言的文本处理器类似。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

  1. if
  2. choose (when, otherwise)
  3. trim (where, set)
  4. f
  5. oreach

搭建环境

搭建数据库

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 '浏览量'
);

INSERT INTO `blog` (`id`, `title`, `author`, `create_time`, `views`) VALUES ('dd82ce6a67da49808352e97fa29f7943', 'Mybatis学习', 'Happy-change', '2022-02-25 22:27:17', 9999);
INSERT INTO `blog` (`id`, `title`, `author`, `create_time`, `views`) VALUES ('7715080c90544c3b99804c07fd3ced21', 'spring学习', 'Happy-change', '2022-02-25 22:27:17', 9999);
INSERT INTO `blog` (`id`, `title`, `author`, `create_time`, `views`) VALUES ('289a485479944c8eb1f471e867fe3622', 'springmvc学习', 'Happy-change', '2022-02-25 22:27:17', 9999);
INSERT INTO `blog` (`id`, `title`, `author`, `create_time`, `views`) VALUES ('3c0444b8961343c594a26c60381a2385', 'springboot学习', 'Happy-change', '2022-02-25 22:27:17', 9999);

创建一个基础maven工程

  1. 导包
  2. 编写配置文件
  3. 编写实体类
@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime; //属性名和字段名不一致
    private int views;
}

在核心配置文件中开启驼峰命名自动映射
在这里插入图片描述

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
  1. 编写
  2. 实体类对应Mapper接口和Mapper.xml文件

IF

接口

 List<Blog> queryBlogIf(Map map);

Mapper

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

测试

@Test
    public void queryBlogIf(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("title","mybatis学习");

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

        sqlSession.close();
    }

trim (where, set)

where元素

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
由此,可对上面IF案例进行优化如下:

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

trim

trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

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

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

set元素

set 元素会动态地在行首插入 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 元素等价的自定义 trim 元素:

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

choose (when, otherwise)

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

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

Foreach

对集合进行遍历(尤其是在构建 IN 条件语句的时候)

select * from user where 1=1 and (id=1 or id=2 or id=3)
<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
    </foreach>
  </where>
</select>

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

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

<!--select * from blog where 1=1 and (id=1 or id = 2 or id = 3)
    传递的map可以传递一个集合
-->
<select id="queryBlogForearch" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open = "and (" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>
@Test
public void queryBlogForearch(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    ArrayList<Integer> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    ids.add(3);
    map.put("ids",ids);
    List<Blog> blogs = mapper.queryBlogForearch(map);
    for (Blog blog: blogs){
        System.out.println(blog);
    }
    sqlSession.close();
}

SQL片段

将公共的部分抽取出来,方便复用!
1、使用sql标签将公共的部分抽取出来

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

2、在需要的地方使用include标签使用

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

注意事项:

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

总结:

  • 所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
  • 动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
  • 建议先在mysql测试sql语句是否能执行成功再进行编写
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值