• Mybatis动态sql语句的使用


    if

    作为条件判断,如果满足if条件,则if标签上的内容便会自动拼接导sql语句中

    1. <select id="xxx" resultType="xxx">
    2. select * from t_xxx where 1=1
    3. <if test="a != '' and a != null"> and a = #{a}if>
    4. <if test="b != '' and b != null"> and b = #{b}if>
    5. <if test="c != '' and c != null"> and c = #{c}if>
    6. select>


    通过if语句对sql语句进行动态拼接以满足不同条件下的开发目标是一个降低耦合的好办法,但是因为sql语句条件下需要and 或者 or 连接条件,所以单单使用if语句并不能很好的解决问题,这个使用就可以在连接if语句之前加上一个永真语句就可以解决,也可以和后面的语句配合使用。

    where

    where是一个连接语句一般用来和if配合使用

    若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
    若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的 and去掉

    1. <select id="xxx" resultType="xxx"> select * from t_xxx
    2. <where>
    3. <if test="a != '' and a != null"> a = #{a}if>
    4. <if test="b != '' and b != null"> and b = #{b}if>
    5. <if test="c != '' and c != null"> and c = #{c}if>
    6. where>
    7. select>

    trim

    trim用于去掉或添加标签中的内容

    prefix:在trim标签中的内容的前面添加某些内容

    prefixOverrides:在trim标签中的内容的前面去掉某些内容

    suffix:在trim标签中的内容的后面添加某些内容

    suffixOverrides:在trim标签中的内容的后面去掉某些内容

    使用trim也可以很好的解决if语句添加多或者少的问题

    1. <select id="xxx" resultType="xxx"> select * from t_xxx
    2. <trim prefix="where" suffixOverrides="and">
    3. <if test="a != '' and a != null"> a = #{a}if>
    4. <if test="b != '' and b != null"> and b = #{b}if>
    5. <if test="c != '' and c != null"> and c = #{c}if>
    6. trim>
    7. select>

    choose、when、otherwise

    相当于if...else if...else

    就是和Java语法完全相同就是换了一个名称

    1. <select id="xxx" resultType="xxx">
    2. select * from t_xxx <where>
    3. <choose>
    4. <when test="a != '' and a != null"> a = #{a}when>
    5. <when test="b != '' and b != null"> b = #{b}when>
    6. <when test="c != '' and c != null"> c = #{c}when>
    7. choose>
    8. where>
    9. select>

    foreach

    循环语句用于实现批量添加或者批量删除或者批量修改

    1. <insert id="xxxx">
    2. insert into t_xxx values
    3. <foreach collection="xxx" item="xxx" separator=",">
    4. (null,#{xxx.x},#{xxx.x},#{xxx.x},#{xxx.x},null)
    5. foreach>
    6. insert>

    collection:用来接受传过来的集合片段

    item:用来取出集合中的一个元素

    separator:用来给每一次给各个循环中间加上连接符

    SQL片段

    sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入

    1. <sql id="Columns"> xxx,xxx,xxx,xxx,xxxsql>
    2. select <include refid="Columns">include> from t_xxx

    一直用 * 在未来开发中是不规范的,因为*其实在数据库内部也是发生转换变成全部属性的,所以直接写就可以直接避免转换的步骤,但是每次都写难免麻烦,这个时候就可以把片段变成sql片段就可以直接调取


    以上就是关于动态sql的基本标签的认识啦

    如有错误欢迎指出

  • 相关阅读:
    人唯有在能够感觉自己有价值时,才有勇气。
    什么是堡垒机
    【LeetCode: 901. 股票价格跨度 | 单调栈】
    苹果平板可以用别的电容笔吗?电容笔和Apple pencil区别
    JDK自带的序列化框架使用
    抖音实战~手机号验证码一键注册登录流程(限制手机终端登录)
    windows系统redis和ARDM(redis客户端)下载安装步骤【非常详细】
    【Flutter】设计原则(2)深入解析 SOLID 原则的应用
    电脑桌面文件删除了怎么恢复?分享3个技巧,你见过第3个吗?
    HTTP如何自动跳转到HTTPS,免费SSL证书如何获取
  • 原文地址:https://blog.csdn.net/qq_51260764/article/details/126165507