Mybatis inserts data dynamically (using trim tags)

Mybatis inserts data dynamically (using trim tags)


Sometimes we control the same table, but the incoming parameters are not fixed, and the fields of the operation table are not fixed, so we need to use mybatis to dynamically insert. .xml is as follows:

<insert id="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>
)
</insert>

The problem comes when messageClassify! =null, but when messageCode and messageContent are empty, there will be more commas, so that mybatis reports an error. The correct usage is as follows.xml:

<insert id="insertMessage" parameterType="com.sf.ccsp.member.client.request.MessageReq">
insert cx_customer_message
<trim prefix="(" 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>
</trim>

<trim prefix="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>
</insert>

attributes of the trim tag

  1. prefix: The prefix overrides and augments its content. That is to add a prefix to the sql statement in;
  2. suffix: Suffix overrides and augments its content. Add a suffix to the wrapped sql statement;
  3. prefixOverrides: Prefix judgment conditions. Cancel the specified prefix, such as where;
  4. suffixOverrides: Conditions for suffix judgment. Cancels specified suffixes such as and | or., comma, etc.

Guess you like

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