Mybatis 动态insert语句

 

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>
MyBatis 中,可以使用动态 SQL 来处理批量插入语句。下面是一个示例: ```xml <insert id="batchInsert" parameterType="java.util.List"> INSERT INTO my_table (column1, column2) VALUES <foreach collection="list" item="item" separator=","> (#{item.column1}, #{item.column2}) </foreach> </insert> ``` 上述代码中,我们使用 `<foreach>` 元素来循环遍历传入的 List 参数,并生成对应的插入语句。每个元素的属性值通过 `#{}` 来引用。在循环过程中,使用 `separator` 属性来指定分隔符,这里使用逗号分隔每个插入语句。 接下来,在 Java 代码中调用这个批量插入语句: ```java List<MyObject> myList = new ArrayList<>(); // 添加要插入的对象到 myList 中 try (SqlSession sqlSession = sqlSessionFactory.openSession()) { MyMapper myMapper = sqlSession.getMapper(MyMapper.class); myMapper.batchInsert(myList); sqlSession.commit(); } catch (Exception e) { // 处理异常 } ``` 上述代码中,首先创建一个包含要插入的对象的 List。然后,通过 SqlSession 和 Mapper 接口来执行批量插入操作。最后,提交事务并处理异常。 注意,需要在 MyBatis 的配置文件中配置你的 Mapper 接口和对应的 SQL 映射。这个示例中的 `MyMapper` 需要定义一个与 XML 中 `<insert>` 标签的 id 属性相同的方法。 这就是使用 MyBatis 进行批量插入的动态 SQL 的基本方法。你可以根据具体需求进行调整和扩展。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值