好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

mybatis中xml之trim属性说明

mybatis的xml中trim标签有四个属性

1. prefix 前缀增加的内容

2. suffix 后缀增加的内容

3. prefixOverrides 前缀需要覆盖的内容,一般是第一个判断条件前面的多余的结构,如:第一个判断条件前面多了 ‘and'

4. suffixOverrides 后缀需要覆盖的内容,一般是最后一个数据的后面符号,如:set值的时候,最后一个值的后面多一个逗号‘,'

举几个例子:

1.根据用户姓名和年龄查询用户,有什么值就根据什么条件(目的是说明几个属性用法,可能例子不适用于实际场景中)

?

1

2

3

4

5

6

7

8

9

10

11

12

select * from User where name = 'zhangsan' and age= '20' ;

< select id= 'queryUser' >

         select * from User

         <trim prefix= 'where' prefixOverrides= 'and' >

             <if test= "name != null and name != ''" >

                 name = #{ name }

             </if>

             <if test= "age !=null and age !=''" >

                 and age = #{age}

             </if>

         </trim>

< select >

上面例子是很常规的一个写法,第一个条件前面没有任何符号,第二个条件要加上and,否则sql语句会报错。很理想的状态是第一个和第二个都有值,但是既然判断,说明也可能会没有值,当第一个name没有值的时候,这个时候sql语句就会是

select * from User where and age='',很明显这个sql语句语法存在问题。在这里标签属性prefixOverrides就起作用了,它会让前缀where覆盖掉第一个and。覆盖之后的是:select * from User where age='';

前缀加上where就不说,因为属性 prefix='where',这个where 也可以写在<trim>标签的外面,这样此处就无需用到属性prefix了。

现在有更方便的标签了,就是<where>,用这个标签效果一样的,会忽略掉第一个符合条件前面的符号。

?

1

2

3

4

5

6

7

8

9

select * from User

< where >

              <if test= "name != null and name != ''" >

                 name = #{ name }

             </if>

             <if test= "age !=null and age !=''" >

                 and age = #{age}

             </if>

</ where >

如果第一个name值是null,则age前面的and会被忽略掉。

再说说另两个属性,suffix和suffixOverrides。

如:更新用户的信息,哪些字段有值就更新哪些字段,sql语句如下:

?

1

2

3

4

5

6

7

8

9

10

11

< update id= "updateUser" >

     update User

     <trim prefix= "set" suffixOverrides= "," suffix= "where id='1'" >

         <if test= "name != null and name != ''" >

             name =#{ name },

         </if>

         <if test= "age != null and age !=''" >

             age=#{age},

         </if>

     </trim>

</ update >

本例中最后一个条件中的逗号[,]会被后缀覆盖掉,本例中的后缀是where id =‘1';

OK,纯属为了说明四个属性怎么使用的,具体里面的值会根据具体需求而定。希望举一反三~

trim标签的使用场景

使用trim标签去除多余的逗号

如果红框里面的条件没有匹配上,sql语句会变成如下:

?

1

INSERT INTO role(role_name,) VALUES (roleName,)

插入将会失败。

做如下修改:

其中最重要的属性是

?

1

suffixOverrides= ","

表示去除sql语句结尾多余的逗号.

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/chenpuzhen/article/details/89643861

查看更多关于mybatis中xml之trim属性说明的详细内容...

  阅读:16次