Mybatis 动态insert语句

MyBatis将Sql语句写在配置xml文件,免去硬编码,业务需求改变时改sql即可。本文记录个人学习MyBatis动态insert语句的笔记,MyBatis通过prefix、suffix、suffixOverrides解决插入字段数量不确定问题,实现动态insert语句。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mybatis的一个比较先进的思想是把Sql语句写在了配置xml文件(也支持注解),通过配置文件的方式,免去了一般软件开发的硬编码,当业务需求改变的时候,只需要更改sql语句即可!
下面是个人在学习mybatis动态insert语句的笔记,留着参考!
在写insert子句的时候,由于不知道需要插入多少字段,mybatis通过prefix,suffix,suffixOverrides很好的解决了该问题,实现了动态insert语句。

<insert id="insertSelective" parameterType="com.bootdo.system.domain.LogDO">
    insert into sys_log
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="userId != null">
        user_id,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="operation != null">
        operation,
      </if>
      <if test="time != null">
        time,
      </if>
      <if test="method != null">
        method,
      </if>
      <if test="params != null">
        params,
      </if>
      <if test="ip != null">
        ip,
      </if>
      <if test="gmtCreate != null">
        gmt_create,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="userId != null">
        #{userId,jdbcType=BIGINT},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="operation != null">
        #{operation,jdbcType=VARCHAR},
      </if>
      <if test="time != null">
        #{time,jdbcType=INTEGER},
      </if>
      <if test="method != null">
        #{method,jdbcType=VARCHAR},
      </if>
      <if test="params != null">
        #{params,jdbcType=VARCHAR},
      </if>
      <if test="ip != null">
        #{ip,jdbcType=VARCHAR},
      </if>
      <if test="gmtCreate != null">
        #{gmtCreate,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值