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

posted @   Bonnie_ξ  阅读(74)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示