Java自学之mybatis:动态SQL的where、set、trim标签

学习目的:在Java自学之mybatis:动态SQL之if标签中提到“查询的字段增加,可以继续添加if标签”,但是同时满足了多个查询条件,拼接的SQL语句就会出现语法错误,所以就需要另外一些标签来排除语法错误,本节学习的三个标签都可以达到这个目的。

Part 1

可能出现的语法错误分析:

    <select id="listAllProduct" resultType="Product">
        select * from product_ where
            <if test="name!=numm">
                and name like concat('%',#{name},'%')
            </if>
            <if test="price!=null and price!=0">
                and price>#{price}
            </if>
        </where>
    </select>

当上面两个if同时满足,那么SQL语句就会拼接成select * from product_ where and name like concat('%',#{name},'%') and price>#{price},很明显第一个and是多余的,此时就出现了SQL语法错误。

Part 2

where标签可以自动覆盖第一个and或者or,part 1中的正确配置如下(注意select * from product_后面不用写where,下同):

    <select id="listAllProduct" resultType="Product">
        select * from product_
        <where>
            <if test="name!=numm">
                and name like concat('%',#{name},'%')
            </if>
            <if test="price!=null and price!=0">
                and price>#{price}
            </if>
        </where>
    </select>

Part 3

在修改数据时,要把if标签写在set标签里面。set标签可以自动删除SQL语句if标签末尾多余的“,”

    <update id="updateProduct" parameterType="Product">
        update product_
        <set>
            <if test="name!=null">name=#{name},</if>
            <if test="price!=null">price=#{price}</if>
        </set>
        where id=#{id}
    </update>

如果不使用set标签,当第二个if不成立时,拼装成的SQL语句是:update product_ set name=#{name}, where id=#{id},此时{name}后面的“,”多余,会造成语法错误。上面使用set标签的正确配置就可以自动删除该“,”。

Part 4

trim标签是用户可以自定义的标签,同样也可以实现where标签和set标签所实现的功能。使用trim标签替换where标签和set标签,分别使用下面的配置:

替换where

<trim prefix="WHERE" prefixOverrides="AND |or">
    ......
</trim>

替换set

<trim prefix="SET" suffixOverrides=",">
    ......
</trim>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值