MyBatis中动态SQL

MyBatis是一个非常流行的ORM框架,它的特点是将SQL语句从Java代码中分离出来,从而使代码更具可读性、可维护性和可扩展性。在MyBatis中,我们可以使用动态SQL来动态生成SQL语句,以满足不同的需求。

动态SQL是MyBatis中非常强大的特性之一,它使得我们可以根据不同的条件来生成不同的SQL语句。MyBatis中的动态SQL有以下几种类型:

  1. If语句:通过判断某个条件是否成立,来决定是否包含该语句片段。

  1. Where语句:用于组合查询条件,只有当第一个条件成立时才会包含该语句片段。

<select id="seach" parameterType="user" resultType="user">
        select * from t_user <!-- 模糊查询 -->
        <where>
            <if test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </if>
            <if test="address!=null and address!=''">
                and address like concat('%',#{address},'%')
            </if>
            <if test="phone!=null and phone!=''">
                and phone like concat('%',#{phone},'%')
            </if>
        </where>
    </select>
  1. Set语句:用于更新数据时设置值,只有当更新字段值不为null时才会包含该语句片段。

<update id="updateUser" parameterType="user">
        update t_user<!-- 更新 -->
        <set>
            <if test="username!=null and username!=''">
                username=#{username},
            </if>
            <if test="password!=null and password!=''">
                password=#{password},
            </if>
            <if test="phone!=null and phone!=''">
                phone=#{phone},
            </if>
            <if test="address!=null and address!=''">
                address=#{address},
            </if>
        </set>
        where uid=#{uid};
    </update>
  1. Foreach语句:用于循环处理集合或数组中的数据,可以动态生成多条SQL语句。

<delete id="deleteById" parameterType="delV0" >
        delete from t_user where uid in  <!-- 根据用户uID删除用户数据 -->
        <foreach item="id" collection="ids" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值