mybatis动态SQL

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决 拼接SQL语句字符串时的痛点问题。

1.动态sql之if标签:进行判断,确定是否输出标签中的结果(true--->输出)

根据条件查询员工信息(使用if标签)

List<Emp> getEmpByConditionIf(Emp emp);
 <select id="getEmpByConditionIf" resultType="Emp">
        select * from t_emp  where 1=1
        <if test="empName != '' and empName != null">
              emp_name = #{empName}
        </if>
        <if test="age != '' and age != null">
            and age = #{age}
        </if>
        <if test="gender != '' and gender != null">
            and gender = #{gender}
        </if>
    </select>

2.动态sql之where标签

作用一:若where标签中有条件成立,程序运行时自动编译成where

作用二:会自动将if标签中内容前多余的and去掉,但是内容后的and无法去掉

作用三:若where标签中没有任何一个条件成立,则where标签失效,不生成where标签

根据条件查询员工信息(使用where标签)

List<Emp> getEmpByConditionWhere(Emp emp);
<select id="getEmpByConditionWhere" resultType="Emp">
        select * from t_emp
        <where>
        <if test="empName != '' and empName != null">
            emp_name = #{empName}
        </if>
        <if test="age != '' and age != null">
            and age = #{age}
        </if>
        <if test="gender != '' and gender != null">
            and gender = #{gender}
        </if>
        </where>
    </select>

3.动态sql之choose,when,otherWise标签:相当于java中的if...else if...else

when至少设置一个,otherwise最多设置一个

根据条件查询员工信息(使用choose标签)

List<Emp> getEmpByChoose(Emp emp);
<select id="getEmpByChoose" resultType="Emp">
        select * from t_emp
          <where>
              <choose>
                  <when test="empName != '' and empName != null">
                      emp_name = #{empName}
                  </when>
                  <when test="age != '' and age != null">
                      age = #{age}
                  </when>
                  <when test="gender != '' and gender != null">
                      gender = #{gender}
                  </when>
              </choose>
          </where>
    </select>

4.动态sql之foreach标签:该标签可实现数据的批量操作,之后作用比较大

collection : 设置要循环的数组或集合

item : 用一个字符串表示数组或集合中的每一个数据

separator : 设置每次循环的数据之间的分隔符

open : 设置循环的所有内容以什么开始

close : 设置循环的所有内容以什么结束

批量添加员工信息

void insertMoreEmp(@Param("emps") List<Emp> emps);
<!--批量添加-->
    <insert id="insertMoreEmp">
        insert into t_emp values
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.empName},#{emp.age},#{emp.gender},null)
        </foreach>
    </insert>

批量删除员工信息

    void deleteMoreEmp(@Param("empIds") Integer[] empIds);
<!--批量删除-->
    <delete id="deleteMoreEmp">
        delete from t_emp where emp_id in
            <foreach collection="empIds" item="empId" separator="," open="(" close=")">
                #{empId}
            </foreach>
    </delete>

本文章使用limfx的vscode插件快速发布