Mybatis动态插入数据(使用trim标签)

Mybatis动态插入数据(使用trim标签)

有时我们控制同一张表,但传入的参数不固定,操作表的字段不固定,就要用到mybatis动态插入。.xml如下:

"insertMessage" parameterType="com.sf.ccsp.member.client.request.MessageReq">
       insert cx_customer_message
       (ID,MEMBERID,
         <if test='messageClassify != null and messageClassify != "" '>
             MESSAGEE_CLASSIFY,
         if>
         <if test='messageCode != null and messageCode != "" '>
             MESSAGE_CODE,
         if>
         <if test='messageContent != null and messageContent != "" '>
             MESSAGE_CONTENT
         if>
        )
       values (
         #{id, jdbcType=VARCHAR},
         #{memberId, jdbcType=VARCHAR},
          <if test='messageClassify != null and messageClassify != "" '>
            #{messageClassify, jdbcType=VARCHAR},
          if>
          <if test='messageCode != null and messageCode != "" '>
            #{messageCode, jdbcType=VARCHAR},
          if>
          <if test='messageContent != null and messageContent != "" '>
            #{messageContent, jdbcType=VARCHAR}
          if>
        )

问题来了,当messageClassify !=null,但messageCode 和messageContent 为空时,会多出来逗号,以至于mybatis报错。正确的用法如下.xml:

"insertMessage" parameterType="com.sf.ccsp.member.client.request.MessageReq">
       insert cx_customer_message
        "(" suffix=")" suffixOverrides="," >
          ID,MEMBERID,
          <if test='messageClassify != null and messageClassify != "" '>
             MESSAGEE_CLASSIFY,
          if>
          <if test='messageCode != null and messageCode != "" '>
             MESSAGE_CODE,
          if>
         <if test='messageContent != null and messageContent != "" '>
             MESSAGE_CONTENT,
         if>
        

        "values (" suffix=")" suffixOverrides="," >
          #{id, jdbcType=VARCHAR},
          #{memberId, jdbcType=VARCHAR},
          <if test='messageClassify != null and messageClassify != "" '>
            #{messageClassify, jdbcType=VARCHAR},
          if>
          <if test='messageCode != null and messageCode != "" '>
            #{messageCode, jdbcType=VARCHAR},
          if>
          <if test='messageContent != null and messageContent != "" '>
            #{messageContent, jdbcType=VARCHAR},
          if>
          

trim标签的属性

  1. prefix:前缀覆盖并增加其内容。也就是给中的sql语句加上前缀;
  2. suffix:后缀覆盖并增加其内容。给包裹的sql语句加上后缀;
  3. prefixOverrides:前缀判断的条件。取消指定的前缀,如where;
  4. suffixOverrides:后缀判断的条件。取消指定的后缀,如and | or.,逗号等。

你可能感兴趣的:(mybatis)