MyBatis 标签使用(insert、update、delete、select、foreach、if、where、choose/when/otherwise、sql/include)

1 CRUD标签

1.1 insert标签

作用:插入数据

示例:

<insert id="insert" parameterType="User">
    insert into users(username,password)
    values(#{username},#{password)
</insert>

1.2 update标签

作用:更新数据

示例:

<update id="update" parameterType="User">
    update users
    set password=${password}
    where username=#{username}
</update>

1.3 select标签

作用:获取数据

示例:

<select id="getUserById" parameterType="String" resultType="User">
    select *
    from users
    where username=#{username}
</select>

注:多个不同类型的参数最好使用parameterType="map"

1.4 delete标签

作用:删除指定数据。

示例:

    <delete id="delete">
        delete from users
        where username = #{username}
    </delete>

2 动态SQL标签

2.1 if标签

作用:用于判断传入的参数

示例:

<select id="getUserExtList" resultType="UserExt">
    select T1.username,T1.password
    from users T1
    where 1=1
    <if test="username!=null and username!=''">
        and T1.username like concat('%',#{username},'%')
    </if>
</select>

2.2 where标签

作用:where 标签知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句。而且,若最后的内容是“AND”或“OR”开头的,where 元素也知道如何将它们去除。

示例:

    <select id="getUserList" resultType="com.entity.User">
        select username,password
        from users
        <where>
            <if test="username != null and username != ''">
                username = #{username}
            </if>
            <if test="password != null and password != ''">
                password = #{password}
            </if>
        </where>
    </select>

2.3 foreach标签

作用:循环List参数,得到List中的每一项

示例:

<select id="getUserExtList" resultType="UserExt">
    select T1.username,T1.password
    from users T1
    where 1=1
    <foreach collection="keyList" item="item" open=" and (" close=")" index="index" separator=" or ">
        T1.username like concat('%',#{item},'%')
    </foreach>
</select>

注:更详细的foreach标签使用请查看下面这条博客

Mybatis foreach(循环)标签使用

2.4 choose/when/otherwise

作用:类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

示例:

    <select id="getUserList" resultType="com.entity.User">
        select username,password
        from users
        where 1=1 
        <choose>
            <when test="username != null and username != ''">
                and username = #{username}
            </when>
            <otherwise>
                and (t1.username = '' or t1.username is null)
            </otherwise>
        </choose>
    </select>

2.5 sql/include

作用:重复引用sql片段。

示例:

具体使用步骤请查看以下博客。

MyBatis sql(sql片段)标签使用(定义SQL、引用SQL)icon-default.png?t=L892https://blog.csdn.net/qq_38974638/article/details/119961002

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值