zoukankan      html  css  js  c++  java
  • 三、动态SQL

    动态SQL

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。

    动态SQL的元素
    元素 作用 备注
    if 判断语句 单条件分支判断
    choose、when、otherwise 相当于Java中的switch case when语句 多条件分支判断
    trim、where、set 辅助元素 用于处理一些SQL拼装问题
    foreach 循环语句 在in语句等列举条件常用

    if

    if元素相当于Java中的if语句,它常常与test属性联合使用。现在我们要根据name去查找学生,但是name是可选的,如下所示:

    <select id="selectByName" resultType="com.zl.domain.StudentDomain">
        SELECT * FROM student
        WHERE 1=1
        <if test="name != null and name != ''">
            AND name LIKE concat('%', #{name}, '%')
        </if>
    </select>
    

    choose、when、otherwise

    有些时候我们还需要多种条件的选择,在Java中我们可以使用switch、case、default语句,而在映射器的动态语句中可以使用choose、when、otherwise元素。

    <!-- 有name的时候使用name搜索,没有的时候使用id搜索 -->
    <select id="select" resultType="com.zl.domain.StudentDomain">
        SELECT * FROM student
        WHERE 1=1
        <choose>
            <when test="name != null and name != ''">
                AND name LIKE concat('%', #{name}, '%')
            </when>
            <when test="id != null">
                AND id = #{id}
            </when>
        </choose>
    </select>
    

    where

    上面的select语句我们加了一个1=1的绝对true的语句,目的是为了防止语句错误,变成SELECT * FROM student WHERE这样where后没有内容的错误语句。这样会有点奇怪,此时可以使用元素。

    <select id="select" resultType="com.zl.domain.StudentDomain">
        SELECT * FROM student
        <where>
            <if test="name != null and name != ''">
                name LIKE concat('%', #{name}, '%')
            </if>
        </where>
    </select>
    

    trim

    有时候我们要去掉一些特殊的SQL语法,比如常见的and、or,此时可以使用trim元素。trim元素意味着我们需要去掉一些特殊的字符串,prefix代表的是语句的前缀,而prefixOverrides代表的是你需要去掉的那种字符串,suffix表示语句的后缀,suffixOverrides代表去掉的后缀字符串。

    <select id="select" resultType="com.zl.domain.StudentDomain">
        SELECT * FROM student
        <trim prefix="WHERE" prefixOverrides="AND">
            <if test="name != null and name != ''">
                AND name LIKE concat('%', #{name}, '%')
            </if>
            <if test="id != null">
                AND id = #{id}
            </if>
        </trim>
    </select>
    

    foreach

    foreach元素是一个循环语句,它的作用是遍历集合,可以支持数组、List、Set接口。

        <select id="select" resultType="com.zl.domain.StudentDomain">
            SELECT * FROM student
            WHERE name IN
            <foreach collection="names" open="(" close=")" separator="," item="item">
                #{item}
            </foreach>
        </select>
    
    • collection配置的是传递进来的参数名称
    • item配置的是循环中当前的元素。
    • index配置的是当前元素在集合的位置下标。
    • open和 close配置的是以什么符号将这些集合元素包装起来。
    • separator是各个元素的间隔符。
  • 相关阅读:
    Eclipse连接MySQL数据库(傻瓜篇)
    JMeter监控内存及CPU ——plugin插件监控被测系统资源方法
    fiddler抓取手机端的数据流量包
    python 字典(dictionary)一些方法
    python 循环语句
    Charles 抓 HTTPS 包
    python RSA 加密与签名
    从零开始做一个Jmeter性能测试
    [python之路]变量和字符编码
    [python之路]简单介绍
  • 原文地址:https://www.cnblogs.com/lee0527/p/11917389.html
Copyright © 2011-2022 走看看