zoukankan      html  css  js  c++  java
  • mybatis动态sql详情

    动态SQL是mybatis的强大特性之一,MyBatis的动态SQL是基于OGNL表达式来完成的,它可以帮助我们方便的在SQL语句中实现某些逻辑。
    MyBatis中用于实现动态SQL的元素主要有9个,如下所示:

    元素说明
    <if> 判断语句,用于单分支判断
    <choose>(<when>、<otherwise>) 相当于java的switch···case···default语句,用于多分支判断
    <where>、<trim>、<set> 辅助元素,用于处理一些SQL拼装、特殊字符问题
    <foreach> 循环语句,常用于in语句等列举条件中
    <bind> 从ognl表达式中创建一个变量,并将其绑定到上下文,常用于模糊查询的sql中

    一、if元素

    在mybatis中if是最常用的判断语句,用来进行一些简单的判断,然后进行动态sql的拼接。在使用==的时候需要使用toString()方法,这样更加稳定一些。如下例子所示:

    <select id="dynamicIfTest" parameterType="Blog" resultType="Blog">  
        select * from t_blog where 1 = 1  
        <if test="title != null">    <!-- test属性用于条件判断语句中,用于判断真假 -->
            and title = #{title}  
        </if>  
        <if test="content != null">  
            and content = #{content}  
        </if>  
        <if test="index=='1'.toString()">  
            and index= #{index}  
        </if>  
        <if test="owner != null">  
            and owner = #{owner}  
        </if>  
    </select>  

    二、choose(when,otherwise)元素

    这个类似于switch多分支语句。

    <select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">  
        select * from t_blog where 1 = 1   
        <choose>  
            <when test="title != null">  
                and title = #{title}  
            </when>  
            <when test="content != null">  
                and content = #{content}  
            </when>
            <when test="job !=null and jobs !=''"> 
                and jobs like concat('%',#{jobs},'%')    <!--concat('%',#{jobs},'%')用于拼接操作-->
            </when> 
            <otherwise>  
                and owner = "owner1"  
            </otherwise>  
        </choose>  
    </select> 

    https://www.cnblogs.com/jasonboren/p/11394721.html

    故乡明
  • 相关阅读:
    学生党可以申请的免费学习资源
    ms16-032漏洞复现过程
    宽字节注入浅浅谈!
    access数据库之cookie注入
    web渗透学习方向
    最简单的注入
    snapde的批量数据运算公式
    snapde的批量文件数据过滤保存功能
    五、Snapman多人协作电子表格之——Python脚本
    超大文本文件浏览器Snaptext,支持不限制大小的文本文件浏览
  • 原文地址:https://www.cnblogs.com/luweiweicode/p/15205316.html
Copyright © 2011-2022 走看看