mybatis中的动态sql

说起sql语句,大家在jdbc阶段最为头疼的就是那个五个步骤吧。重复,冗余,繁杂。而mybatis的出现便很好的解决了动态sql的问题。我接下来,就为大家来说一下这个动态sql的巧妙之处吧。

动态SQL的相关学习

  • 首先还是搭建实体类以及插入需要的测试数据

  • @AllArgsConstructor
    @NoArgsConstructor
    @Datapublic 
    class Blog {    
        private int id;    
        private String title;    
        private String author;    
        private Date createTime;    
        private int views;
    }

    IF的学习

  • 查询博客

  • 该查询的要求,要求在author或者title不为空的时候,进行相应的详细查询

  • <select id="getBlogIf" resultType="Blog" parameterType="java.util.Map">
        select *
        from blog
        where true
        <if test="author != null">
            and author = #{author}
        </if>
        <if test="title != null">
            and title = #{title}
        </if>
    </select>

    set的学习

  • 根据要求来进行博客信息的更新

  • <update id="updateBlogMessage" parameterType="java.util.Map">
        update blog
        <set>
            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id = #{id}
    </update>

    choose和otherwise相关

  • <select id="test" resultType="Blog" parameterType="user">
        select *
        from blog
        <where>
            <choose>
                <when test="title != null">
                </when>
                
                <when test="author != null">
                </when>
    
                <otherwise>
                </otherwise>
            </choose>
        </where>
    </select>

    foreach相关

  • 案例:来查询id为哪几位的几条数据,通过foreach来进行传参。

  • Map<String, List<Integer>> map = new HashMap<>();
    List<Integer> numList = new ArrayList<>();
    for (int i = 5; i > 0; i --) {
        numList.add(i);
    }
    map.put("ids", numList);
    List<Blog> blogBetweenRange = mapper.getBlogBetweenRange(map);
    <select id="getBlogBetweenRange" resultType="Blog" parameterType="java.util.Map">
        select *
        from blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>

    总结:所谓的动态SQL,本质上还是SQL语句的拼接,只是我们在SQL语句的层面上去加入了一个执行逻辑的控制代码。

        最后再给大家插播一条小知识:

长知识时间:HashMap的默认大小是2^4也就是16,最大的大小是2^30,并且hashmap的大小只能是2的次方数个。ArrayList的默认大小是10。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值