Mybatis—动态SQL

导读:本篇文章讲解 Mybatis—动态SQL,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1.动态SQL

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

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

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

1.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 '浏览量'
);
  1. 导包(junit、lombok)
  2. 编写配置文件
  3. 编写实体类
@Data
public class Blog {
    private  int id;
    private  String title;
    private  String author;
    private Date createtime;
    private int views;
}
  1. 编写实体类对应的Mapper接口和Mapper.xml文件

1.2、IF

当title为空的时候就不用传值,当title有数据,则将数据取过来做查询,author也一样。

<select id="queryBlogIF" parameterType="map" resultType="pojo.Blog">
        select * from mybatis.blog 
    	#在where标签里面,会自己省去title语句里面的那个and,如果不用where标签,则会出现sql语句拼接错误,不传数据则会自动在拼接sql时where会去掉       
      	<where>
            <if test="title != null">
                and title = #{title}
            </if>
            <if test="author != null">
                and author = #{author}
            </if>
        	</where>
    </select>

测试:

@Test
public void test02(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    map.put("title","热爱java");
    
    List<Blog> blogs = mapper.queryBlogIF(map);
    for (Blog blog:
         blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

1.3、choose(when,otherwise)

相当于是switch语句,满足上面的条件,下面的就不用再选择

<select id="queryBlogChoose" parameterType="map" resultType="pojo.Blog">
    select * from mybatis.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>

测试:

@Test
public void test03(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    //map.put("title","热爱java");
    //map.put("author","二哈");
    map.put("views",999);

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

1.4、trim(where,set)

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>
    </set>
    where id = #{id}
</update>

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

#在where标签里面,会自己省去title语句里面的那个and,如果不用where标签,则会出现sql语句拼接错误,不传数据则会自动在拼接sql时where会去掉 
<where>
            <if test="title != null">
                and title = #{title}
            </if>
            <if test="author != null">
                and author = #{author}
            </if>
        </where>

所谓动态SQL,本质还是SQL语句

1.5、SQL片段

有的时候,会将一些公共部分抽取出来进行复用

1.使用SQL标签抽取公共部分

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

2.在需要使用的地方使用include标签引用即可

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

注意:

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

1.6、Foreach

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

<!--    用来实现sql语句:select * from mybatis.blog where (id = 1 or id = 2 or id = 3)
-->
    <select id="queryBolgForeach" parameterType="map" resultType="pojo.Blog">
        select * from mybatis.blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>
  • collection:是map里面的一个元素,类型是集合
  • item:collection集合里面的单个元素属性
  • open和close:该collection集合左右两边的sql拼接
  • separator:拼接集合中的元素的时候用上面来分割

测试:

@Test
public void test03(){
    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.queryBolgForeach(map);
    for (Blog blog:
            blogs) {
        System.out.println(blog);
    }

    sqlSession.close();
}

总结:动态SQL就是在拼接SQL语句,我们只要保证sql语句的正确性,按照SQL格式去排列组合就行。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/84170.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!