MyBatis 动态SQL

什么是动态SQL?

根据不同的条件生成不同的sql语句

搭建环境

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

1.创建基础工程
2.编写配置文件
3.编写实体类

@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}

4.编写mapper接口和mapper.xml
5.测试

IF

与 java 中 IF 相似,满足条件则拼接Sql

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

Choose(when,otherwise)

  • 有时我们不想应用全部的条件语句,只想从中选择一项,就用choose标签
  • choose与 Java 中的 switch 语句相似,从上到下扫描条件,但凡满足一条,退出choose,如都不满足,走otherwise
<select id="findBlogChoose" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <choose>
            <!-- 如果有title -->
            <when test="title != null">
                and title = #{title}
            </when>
            <!-- 如果有author -->
            <when test="author != null">
                and author = #{author}
            </when>
            <!-- 以上都不满足 -->
            <otherwise></otherwise>
        </choose>
    </where>
</select>

trim(where,set)

  • where标签:取代sql语句中的where关键字,作用是自动帮我们舍弃where后的and/or关键字,避免出现where and x=y的情况
    <select id="findBlogIF" 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>
    
  • set标签:取代sql中的set关键字,并且可以去掉句尾无关多余的逗号
    <update id="update" parameterType="map">
        update blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author},
            </if>
        </set>
            where id = #{id}
    </update>
    

foreach

<!-- 我们传一个万能map,里面有一个集合存要查的id们 -->
<select id="findBlogForEach" parameterType="map" resultType="Blog">
    select * from blog where id in
    <foreach collection="ids" item="id" open="(" close=")" separator=",">
        #{id}
    </foreach>
</select>

总结

动态sql就是在拼接sql语句,我们主要保证sql的正确性,按照sql的格式去排列组合就可以了

建议:先在mysql中写出完整的sql,再对应的去修改成为我们的动态sql。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值