【Mybatis】动态SQL的实现,<where>、<if>、<choose>-<when>、<set>、<foreach>

一、介绍

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。

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

常用的标签:
if
choose (when, otherwise)
where
set
foreach

二、if

介绍:

可以通过用户传递的指定的参数进行条件搜索,对用户参数进行的自动匹配,简化开发代码量。

实现:
配置文件:

	如果用户传递的参数中有title和author,那么就通过用户传递的参数进行条件搜索。
    <select id="selBlogIF" 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 selBlogIF(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title","Springboot");
        map.put("author","赵六");
        
        List<Blog> blogs = mapper.selBlogIF(map);
        
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

在这里插入图片描述

三、where

介绍:

我们可以发现,在【一】中的代码中有这么一个代码片段“1=1”,很显然这个在SQL语句中是不应该使用的。但是不加“1=1”,那么【1】中的if是否实现都会报错。
.
当if未实现时,select * from blog where。很明显语句是不对的
.
当if实现时,select * from blog where and title=?。很明显语句也是不对的

为了解决上面的问题,我们引入一个< where>标签。

实现:

配置文件:

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

当where中的if没有实现时,where不会显示。如下:
select * from blog
当where中只有一个if实现时,where会显示,且限制条件的前面会自动的去掉and
总而言之,就是很智能


测试代码:

    @Test
    public void selBlogWhere(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("title","SpringBoot");
        map.put("views",520);

        List<Blog> blogs = mapper.selBlogWhere(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }

在这里插入图片描述

四、choose

介绍:

在Mybatis中的choose的作用相当于java中的switch,这样说大家应该很容易明白了

实现:
配置文件:

    <select id="selBlogChoose" parameterType="map" resultType="blog">
        select * from `blog`
        <where>
            <choose>
                <when test="title != null">`title` = #{title}</when>
                <when test="author != null">`author` = #{author}</when>
                <when test="id != null">`id` = #{id}</when>
                <otherwise>`views` > 500 </otherwise>
            </choose>
        </where>
    </select>

when:相当于java中的case,其作用和if很相似
otherwise:相当于java中default


测试代码:

    @Test
    public void  selBlogChoose(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("title","爱上java");

        List<Blog> blogs = mapper.selBlogChoose(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }

在这里插入图片描述

五、set

介绍:

在更新(update)操作的时候,我们需要set来设置修改后的新值。
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

实现:
测试代码:

    <update id="updateBlogSet" parameterType="map">
        update `blog`
        <set>
            <if test="title != null">`title`=#{title}, </if>
            <if test="author != null">`author`=#{author}, </if>
            <if test="create_time != null">`create_time`=#{create_time}</if>
        </set>
        where `id` = #{id}
    </update>

测试代码:

    @Test
    public void updateBlogSet(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("id","f3971c737167451a82412f66532fcb48");
        map.put("title","爱上C++");
        map.put("views",521);

        mapper.updateBlogSet(map);

        sqlSession.commit();
        sqlSession.close();

    }

在这里插入图片描述

六、foreach

介绍:

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

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

实现1:
配置文件:

<!--    select * from `blog` where (`id`=? or `id`=?,...)-->
    <select id="selBlogForeach" parameterType="map" resultType="blog">
        select * from `blog`
        <where>
            <foreach collection="idList" item="id" open="(" separator="or" close=")">
                `id`=#{id}
            </foreach>
        </where>
    </select>

测试代码:
    @Test
    public void selBlogForeach(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList<String> idList = new ArrayList<String>();
        idList.add("2ef53d21c8bb435f8ba97208d3b81d68");
        idList.add("1405078de3df4f2f9a1ff4deb76ebebc");
        map.put("idList",idList);

        List<Blog> blogs = mapper.selBlogForeach(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();

    }

在这里插入图片描述



实现2:
配置文件:

<!--    select * from `blog` where `id` in (id1,id2,...)-->
    <select id="selBlogForeach2" parameterType="map" resultType="blog">
        select * from `blog`
        <where>
            <if test="idList != null">
                `id` in
                <foreach collection="idList"  item="id" open="(" separator="," close=")">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

测试代码:
    @Test
    public void selBlogForeach2(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList<String> idList = new ArrayList<String>();
        idList.add("2ef53d21c8bb435f8ba97208d3b81d68");
        idList.add("1405078de3df4f2fgdgrdrdfdfdebebc");
        idList.add("c051172bc30c48ca822eb06d72dd5c87");
        idList.add("1405078de3df4f2f9a1ff4deb76ebebc");
        idList.add("2ef53d21c8bb435f8ba9565595956568");
        idList.add("1405078de3888888881ff4deb76ebebc");
        map.put("idList",idList);

        List<Blog> blogs = mapper.selBlogForeach2(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值