天天看點

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>