mybatis中---动态sql

1、sql片段的复用

    <sql id="唯一标识">
        select *
    </sql>

    <select id="方法名" resultType="com.gao.entity.XXX类">
        <include refid="唯一标识"/>
        from 数据库表名
    </select>

 

2、where标签

  where用于条件查询

  可以自动去除条件中的And或者Or关键字

  当where条件中所有的条件都不满足时,where关键字不会出现在sql语句中

案例:

复制代码
    <select id="方法名" resultType="com.gao.entity.XXX类">
        select *
        from 数据库表名
        <where>
            <if test="方法参数名 != null And 方法参数名.length > 0">
                And 数据库字段名 = #{方法参数名}
            </if>
            <if test="方法参数名 != null And 方法参数名.length > 0">
                Or 数据库字段名 = #{方法参数名}
            </if>
        </where>
    </select>
复制代码

 

3、set标签

  set标签中至少保证一个条件成立

复制代码
    <update id="方法名" parameterType="com.gao.entity.XXX类">
        update 数据库表名
        <set>
            <if test="方法参数名 != null And 方法参数名.length > 0">
                数据库字段名 = #{方法参数名},
            </if>
            <if test="方法参数名 != null And 方法参数名.length > 0">
                数据库字段名 = #{方法参数名},
            </if>
        </set>
    </update>
复制代码

 

4、trim标签(where、set案例)

  prefix:前缀  处理条件 where 或 set

  prefixOverrides:去除多余的And或者Or

  suffixOverrides:去掉多余的逗号

案例:where

复制代码
    <select id="方法名" resultType="com.gao.entity.XXX类">
        select *
        from 数据库表名
        <trim prefix="where" prefixOverrides="and|or">
            <if test="方法参数名 != null And 方法参数名.length > 0">
                And 数据库字段名 = #{方法参数名}
            </if>
            <if test="方法参数名 != null And 方法参数名.length > 0">
                Or 数据库字段名 = #{方法参数名}
            </if>
        </trim>
    </select>
复制代码

案例:set

复制代码
    <update id="方法名" parameterType="com.gao.entity.XXX类">
        update 数据库表名
        <trim prefix="set" suffixOverrides=",">
            <if test="方法参数名 != null And 方法参数名.length > 0">
                数据库字段名 = #{方法参数名},
            </if>
            <if test="方法参数名 != null And 方法参数名.length > 0">
                数据库字段名 = #{方法参数名},
            </if>
        </trim>
        where id=#{id}
    </update>
复制代码

 

5、if标签

  一般是配合其他标签使用,用于条件的判断

 

6、foreach标签

  集合迭代,通常用在in条件语句中

案例:

 

7、choose标签

  类似于java中switch语句

  when

  otherwise 

 
posted @   向大海  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示