The use of trim tags in mybatis dynamic sql statements

The trim tag is a formatted tag that can complete the function of set or where tag, as follows:

  select * from user 

  <trim prefix="WHERE" prefixoverride="AND |OR">

    <if test="name != null and name.length()>0"> AND name=#{name}</if>

    <if test="gender != null and gender.length()>0"> AND gender=#{gender}</if>

  </trim>

  If the values ​​of name and gender are not null, the printed SQL is: select * from user where (1) name = 'xx' and gender = 'xx'

  In the place of (1), there is no first and, and the meanings of the above two attributes are as follows:

  prefix: prefix      

  prefixoverride: remove the first and or or

 

  update user

  <trim prefix="set" suffixoverride="," suffix=" where id = #{id} ">

    <if test="name != null and name.length()>0"> name=#{name} , </if>

    <if test="gender != null and gender.length()>0"> gender=#{gender} ,  </if>

  </trim>

  If the values ​​of name and gender are not null, the printed SQL is: update user set name='xx' , gender='xx' (2) where id='x'

  There is no comma in (2), and a set prefix and a where suffix are automatically added. The meanings of the above three attributes are as follows, and the meaning of prefix is ​​as above:

  suffixoverride: remove the last comma (it can also be other tokens, like the and in the prefix above)

  suffix: suffix

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325513998&siteId=291194637