mybatis动态sql

动态sql 就是指 根据不同的条件生成不同的sql

拓展 UUID 唯一的随机数
用法 封装到工具类中 要用可以直接调用

package com.mumu.util;

import java.util.UUID;

public class Uuid {


public static String  getuuid(){
		//把  -  去掉
    String s = UUID.randomUUID().toString().replaceAll("-", "");
    return  s;
}

}

动态sql 我们来先了解


<if test="条件表达式 "  > sql语句    </if>
if标签   就是判断的意思  如果test=“ 条件表达式成立”  
那么将执行 后面的sql语句

    <select id="getbolg" parameterType="map" resultType="blog">
        select  * from mybatis.blog where 
            <if test="title!=null">
                  title=#{title}

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

    </select>

但是由于条件的不缺定性 条件不同时 where后面不知道要不要接and或者or
所以我们一般在使用筛选时 都用个where标签 把它们包主


    <select id="getbolg" parameterType="map" resultType="blog">
        select  * from mybatis.blog
        <where>
            <if test="title!=null">
                  title=#{title}

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


        </where>

    </select>

choose、when、otherwise 标签

/**    choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。
 当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,
#         choose 为 switch,when 为 case,otherwise 则为 default。 -->*/
`    <select id="getbolg" parameterType="map" resultType="blog">
    select  * from mybatis.blog
    <where>
    <choose>
            <when test="title!=null">
                title=#{title}
            </when>
            <otherwise>


            </otherwise>

    </choose>
    </where>

    </select>``

trim、where、set 标签
由于不知道什么时候要用set 设置修改数据库 所以我们直接用set标签的形式
将它们包住 直接不用写set字段

 <update id="update" parameterType="map">
        update  mybatis.blog
        <set>

            <if test="title!=null">
                 title=#{title},
            </if>
            <if test="author!=null">
                 author=#{author},
            </if>
            <if test="views!=null">
                 views=#{views}
            </if>
        </set>
            where id=#{id}


    </update>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值