Mybatis在映射文件中常用标签

【1】if标签

通过if标签我们可以动态的传入参数,以帮助我们适应不同的情景下的sql查询。

案例:

select * from user
        <where>
            <if test="id != 0"> id = #{id}</if>
            <if test="username != null"> and username = #{username}</if>
            <if test="password != null"> and password = #{password}</if>

        </where>

这样,届时传入一个对象,就可以根据id进行查询,可以根据用户名进行查询,或者根据用户名和密码进行查询。

【2】where标签

通过where标签,在sql语句中,对where关键字进行补足,并且当进行and等关键字操作并且不用担心and是否是多余的情况

案例:

select * from user
        <where>
            <if test="id != 0"> id = #{id}</if>
            <if test="username != null"> and username = #{username}</if>
            <if test="password != null"> and password = #{password}</if>
        </where>

通过where关键字,我们就不需要对如果id == 0的时候,我们就不用担心 select * from user where and username = ***的情况了,Mybatis会自动将and去除的。

注意:and关键字只能放在开头

username = #{username} and 错误

【3】set标签

当我们使用update更新语句的时候,可以使用set标签。补足set关键字,并且避免“,”的影响。

案例:

update user
        <set>
            <if test="name != null">
                name = #{name},
            </if>
            <if test="age != -1">
                age = #{age},
            </if>
        </set>
        <where>
            id = #{id}            
        </where>

这样,即使age != -1条件成立,age = #{age},也不会影响语句,因为Mybatis会将去除掉。

【4】trim

trim标签可以结合insert语句,进行操作插入操作,可以去除“(”,“)”,“,”等。我感觉比较鸡肋.....

prefix:表示前缀字符

suffix:表示后缀字符

suffixOverrides:表示分隔字符

案例:

insert into
            user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            id,
            <if test="name != null">
                name,
            </if>
            <if test="age != -1">
                age,
            </if>
        </trim>
        values
        <trim prefix="(" suffix=")" suffixOverrides=",">
            null,
            <if test="name != null">
                #{name},
            </if>
            <if test="age != -1">
                #{age},
            </if>
        </trim>

【5】foreach

foreach标签,循环标签,可以对传入的数据进行遍历操作,适合in等关键字。

collection:集合内容

open:前缀字符

close:后缀字符

item:元素

separator:分隔符

案例:

delete from
            user
        <where>
            id in 
            <foreach collection="list" open="(" close=")" item="item" separator=",">
                #{item}
            </foreach> 

        </where>

【6】sql与include

当映射文件中,重复语句太多的时候,可以通过sql进行抽取,然后通过include关键字进行引入。

案例:

<sql id="select_user">
        select name , age
    </sql>
    <select id="select02" resultType="user">
        <include refid="select_user"/> from user
    </select>

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值