How to perform batch data insertion in MyBatis?
In MyBatis, we can use the foreach tag to achieve batch data insertion. The specific steps are as follows:
- Create a Mapper interface that defines an insertBatch method for inserting data in batches.
public interface UserMapper {
void insertBatch(List<User> userList);
}
- In the XML file corresponding to the Mapper interface, write the SQL statement for the insertBatch method and use the foreach tag to insert data in a loop.
<insert id="insertBatch" parameterType="java.util.List">
insert into user (name, age) values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.name}, #{item.age})
</foreach>
</insert>
- Call the insertBatch method in the code, and pass in the list of data that needs to be inserted.
List<User> userList = new ArrayList<>();
userList.add(new User("Alice", 25));
userList.add(new User("Bob", 30));
userMapper.insertBatch(userList);
By following the above steps, it is possible to achieve batch data insertion in MyBatis.