• Mybatis动态SQL(DynamicSQL)


    目录

    1. if

    2. where

    3. ​​​​​​​trim

    4. choose when otherwise

    5. foreach

    6. sql


    1. if

    if通过test属性中的表达式判断标签中的内容是否有效(是否拼接到sql中)

    条件判断,test为条件语句

    2. where

    同sql中where

    where: where中有条件成立,则sql会拼接上

    where 可以去除多余的and

    where都不成立时,去除sql条件中前多余的and去掉,但是不能除去之后的and

    3. ​​​​​​​​​​​​​​trim

     

    prefix/suffix:在标签内容前后添加指定的内容

    prefixOverrides/suffixOverrides: 在标签中前面或后面去掉指定的内容

    1. <select id="getEmpByCondition" resultType="emp">
    2. select * from t_emp
    3. <trim prefix="where" suffixOverrides="and">
    4. <if test="empName != null and empName != ''" >
    5. emp_name = #{empName} and
    6. if>
    7. <if test="age != null and age != ''" >
    8. age = #{age} and
    9. if>
    10. <if test="gender != null and gender != ''" >
    11. gender = #{gender} and
    12. if>
    13. trim>
    14. select>

    4. choose when otherwise

    choose 主要用于分支判断,类似于 java 中的switch case default

    1. <select id="getEmpByChoosen" resultType="emp">
    2. select * from t_emp
    3. <where>
    4. <choose>
    5. <when test="empName != null and empName != ''" >
    6. emp_name = #{empName}
    7. when>
    8. <when test="age != null and age != ''" >
    9. age = #{age}
    10. when>
    11. <when test="gender != null and gender != ''" >
    12. gender = #{gender}
    13. when>
    14. choose>
    15. where>
    16. select>

    5. foreach

    代码中所示,批量插入,遍历list中的元素,一次放入sql中

    • foreach:遍历
    • collection: 所要添加的集合
    • item:集合中每个实例对象
    • separator:遍历完成后的分隔符
    • open="xx" sql语句以xx开始
    • close="xx" sql语句以xx结束
    1. <insert id="insertEmpList" >
    2. insert into t_emp values
    3. <foreach collection="emplist" item="emp" separator=",">
    4. (null, #{emp.empName}, #{emp.age}, #{emp.gender},null)
    5. foreach>
    6. insert>

    6. sql

    sql拼接

    可以将sql中的某一部分收取出来,封装成一个xxx标签,通过标签插入到sql中合适的地方,从而进行拼接sql

    1. <sql id="empColumn">
    2. emp_id, emp_name, age, gender,dept_id
    3. sql>
    4. <select id="getEmpByChoosen" resultType="emp">
    5. select <include refid="empColumn"/> from t_emp
    6. select>

  • 相关阅读:
    大坝安全监测站 一体式监测站
    MySQL高级10-InnoDB引擎存储架构
    24/8/6算法笔记 支持向量机
    【面试题精讲】构造方法有哪些特点?是否可被 override?
    js的基础
    Shell编程之第一讲——基础知识认识
    C语言函数复习全解析:参数、无参、嵌套与递归
    28道Webpack面试题及答案
    中英文说明书丨艾美捷BrdU细胞增殖检测试剂盒
    JaveEE进阶----Spring Web MVC入门
  • 原文地址:https://blog.csdn.net/qq_41950447/article/details/127837143