• 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的基本标签的认识啦

    如有错误欢迎指出

  • 相关阅读:
    C++ partition()和stable_partition()函数用法详解(深入了解,一文学会)
    leetcode竞赛:20220904双周赛
    NFC技术的定义通信方式
    HTTP头部信息解释分析(详细整理)(转载)
    freeRTOS学习day2任务创建(静态创建)
    【无公网IP】在公网环境下Windows远程桌面Ubuntu 18.04
    ASPICE标准快速掌握「5.1. ASPICE与ISO/IEC 33004」
    数据库原理及应用实验报告-实验10-触发器
    【华为OD机试真题 python】乱序整数序列两数之和绝对值最小 【2022 Q4 | 100分】
    MySQL 视图简介
  • 原文地址:https://blog.csdn.net/qq_51260764/article/details/126165507