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:

  1. Create a Mapper interface that defines an insertBatch method for inserting data in batches.
public interface UserMapper {
    void insertBatch(List<User> userList);
}
  1. 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>
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds