2021-10-06 Mybatis中动态SQL

    //添加字段
    int insertBlog(Map map);

    //根据传入不同的字段拼接查询
    List<Blog> queryBlogIf(Map map);

    //根据传入不同的字段查询
    Blog queryBlogWhen(Map map);

    //根据传入不同的字段修改
    int updateBlogSet(Map map);

    //根据传入id个数循环查询
    List<Blog>  queryBlogForeach(Map map);

7.1if和where标签

if标签用于判断,如果test属性中的条件满足,则动态的拼接至sql语句后面

where标签动态的添加where关键字,也可以动态的删除and关键字

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

7.2choose when otherwise

     用于选择判断,用法类似if else结构 当满足when的条件后就拼接当前sql,而后面的when将不再执行,otherwise为当所有条件都不满足时执行,如果没有符合的条件,一般会返回所有数据。

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

7.3 trim where set

trim可以自定义规则,比如set和where就是由trim实现

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

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>
​
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

set则将会动态的移除最后一个逗号

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

7.4 foreach

    foreach用来动态的循环获取传入的集合中的值进行遍历,其中collection为传入的参数即map中的键,item为取出的参数项,open为遍历的结果集的前缀,close为后缀,separator则为结果的分隔符

    <select id="queryBlogForeach" parameterType="map" resultType="blog">
        select * from blog
        <where>
            id in
            <foreach collection="ids" item="id" open="(" close=")" separator=",">
                #{id}
            </foreach>
        </where>
    </select>

7.5 sql片段 include(sql复用)

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值