MyBatis 动态SQL标签汇总

本文介绍了MyBatis中用于构建动态查询的几个关键标签,包括`if`、`where`、`trim`、`choose/when/otherwise`和`foreach`。这些标签允许在XML映射文件中根据条件动态生成SQL查询,提高代码的灵活性和可维护性。例如,`if`标签用于条件判断,`trim`可以处理多余的AND或WHERE,`foreach`则用于遍历集合并构建IN语句。
摘要由CSDN通过智能技术生成

if 标签

<select id="getEmpByCondition" resultType="com.xy.mybatis.dynamic.pojo.Emp">
    select * from emp
    where 1 = 1
    <if test="name != '' and name != null">
        and name = #{name}
    </if>
    <if test="age != '' and age != null">
        and age = #{age}
    </if>
</select>

where 标签

<select id="getEmpByCondition" resultType="com.xy.mybatis.dynamic.pojo.Emp">
    select * from emp
    <where>
        <if test="name != '' and name != null">
            name = #{name}
        </if>
        <if test="age != '' and age != null">
            and age = #{age}
        </if>
    </where>
</select>

trim 标签

<select id="getEmpByCondition" resultType="com.xy.mybatis.dynamic.pojo.Emp">
    select * from emp
    <trim prefix="where" suffixOverrides="and" prefixOverrides="and" suffix="order by id desc">
        <if test="name != '' and name != null">
            name = #{name}
        </if>
        <if test="age != '' and age != null">
            and age = #{age}
        </if>
    </trim>
</select>

choose、when、otherwise 标签

<select id="getEmpByChoose" resultType="com.xy.mybatis.dynamic.pojo.Emp">
    select * from emp
    <where>
        <choose>
            <when test="name != '' and name != null and age != '' and age != null">
                name = #{name} and age = #{age}
            </when>
            <when test="age != '' and age != null">
                age = #{age}
            </when>
            <when test="name != '' and name != null">
                name = #{name}
            </when>
            <otherwise>
                1 = 1
            </otherwise>
        </choose>
    </where>
</select>

foreach 标签

<select id="getEmpByIds" resultType="com.xy.mybatis.dynamic.pojo.Emp">
    select * from emp
    <foreach collection="ids" item="id" open="where id in (" close=")" separator=",">
        #{id}
    </foreach>
</select>

sql、include 标签

<sql id="base">
    select id, name, age
    from emp
</sql>

<select id="getEmpByIds" resultType="com.xy.mybatis.dynamic.pojo.Emp">
    <include refid="base"/>
    <foreach collection="ids" item="id" open="where id in (" close=")" separator=",">
        #{id}
    </foreach>
</select>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值