MyBatis Batch Insert: Step-by-Step Guide
MyBatis offers a method for batch inserting data, which can be implemented through the following steps:
- Create a collection (such as a list or array) that includes the new data.
- Define a method in the Mapper interface that accepts a parameter of collection type.
void insertBatch(List<YourEntity> list);
- for each
<insert id="insertBatch" parameterType="java.util.List">
INSERT INTO your_table (column1, column2, ...)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.property1}, #{item.property2}, ...)
</foreach>
</insert>
- Call the method of the Mapper interface in Java code, passing in a collection as a parameter.
List<YourEntity> list = new ArrayList<>();
// 添加数据到list中...
yourMapper.insertBatch(list);
The above steps can be used to bulk insert data using MyBatis. It is important to adjust the table name, column names, and entity class property names according to the actual situation.