温馨提示×

mybatis批量insert语句怎么写

小亿
89
2023-12-23 18:43:13
栏目: 编程语言

MyBatis提供了<foreach>标签来处理批量插入语句。下面是一个示例:

<insert id="insertBatch" parameterType="java.util.List">
  INSERT INTO table_name (column1, column2)
  VALUES
  <foreach collection="list" item="item" separator=",">
    (#{item.column1}, #{item.column2})
  </foreach>
</insert>

这个示例中,insertBatch是SQL映射文件中的一个insert语句的id。parameterType指定了传入的参数类型为List。使用<foreach>标签遍历传入的List,并将每个元素的属性值插入到对应的列中。

例如,假设有以下Java对象模型:

public class MyObject {
  private int column1;
  private String column2;
  
  // getters and setters
}

在Java代码中,你可以调用上述的insert语句:

List<MyObject> list = new ArrayList<>();
// 添加MyObject对象到list中

mybatisSession.insert("insertBatch", list);

注意:在使用批量插入语句时,请确保数据库驱动程序支持批量操作。

0