How to perform batch insert operations in MyBatis?
In MyBatis, batch insert operations can be achieved by using either the insertList method or the foreach tag.
- add a list
<insert id="batchInsert" parameterType="java.util.List">
insert into table_name (column1, column2, column3)
values
<foreach collection="list" item="item" separator=",">
(#{item.property1}, #{item.property2}, #{item.property3})
</foreach>
</insert>
When calling this method in Java code, pass in a List containing multiple objects, with each object containing the data to be inserted.
- for each
<insert id="batchInsert" parameterType="java.util.List">
insert into table_name (column1, column2, column3)
values
<foreach collection="list" item="item" separator=",">
(#{item.property1}, #{item.property2}, #{item.property3})
</foreach>
</insert>
Passing a List into Java code, and then using a foreach tag in SQL to iterate through the elements in the List for insertion.
It is important to note that bulk insertion operations in MyBatis may incur performance loss, as each insertion generates a new SQL statement to execute. For better performance with large amounts of data, it is recommended to use batch insertion methods.