How to bulk insert data in MyBatis?
MyBatis offers a way to bulk insert data by using the foreach tag. Here is an example.
- Write the SQL statement for batch insert data in the Mapper XML file as shown below:
<insert id="batchInsert" parameterType="java.util.List">
insert into user (name, age) values
<foreach collection="list" item="item" separator=",">
(#{item.name}, #{item.age})
</foreach>
</insert>
- Define a method in the Mapper interface for batch data insertion.
void batchInsert(List<User> userList);
- Call the method in the code and pass in the list of new data to be added.
List<User> userList = new ArrayList<User>();
userList.add(new User("John", 25));
userList.add(new User("Jane", 28));
userMapper.batchInsert(userList);
In the above example, User is a JavaBean with properties of name and age. The userList is a list of new data to be added, which will be inserted into the database in bulk by calling the batchInsert method. The Mapper XML file uses the foreach tag to concatenate each data item into an SQL statement.