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 @ 2022-11-14 01:29  向大海  阅读(26)  评论(0编辑  收藏  举报