How is the list used in MyBatis?

The list in MyBatis is used to perform batch operations in mapping files. It allows you to insert, update, or delete multiple objects from a parameter list at once. Here is an example of how to use the list in MyBatis:

  1. Insert multiple objects: You can use the foreach tag to loop through the objects in the list and insert them into the database.

Example of mapping files:

<insert id="insertUsers" parameterType="java.util.List">
  INSERT INTO users (id, name, age) VALUES
  <foreach collection="list" item="user" separator=",">
    (#{user.id}, #{user.name}, #{user.age})
  </foreach>
</insert>

Example Java code:

List<User> userList = new ArrayList<>();
userList.add(new User(1, "Alice", 20));
userList.add(new User(2, "Bob", 25));
userList.add(new User(3, "Charlie", 30));

sqlSession.insert("insertUsers", userList);
  1. Update multiple objects: you can use the foreach tag to loop through the objects in the list and update the database.

Example of mapping file:

<update id="updateUsers" parameterType="java.util.List">
  <foreach collection="list" item="user" separator=";">
    UPDATE users SET name = #{user.name}, age = #{user.age} WHERE id = #{user.id}
  </foreach>
</update>

Example Java code:

List<User> userList = new ArrayList<>();
userList.add(new User(1, "Alice", 21));
userList.add(new User(2, "Bob", 26));
userList.add(new User(3, "Charlie", 31));

sqlSession.update("updateUsers", userList);
  1. Delete multiple objects: You can use a foreach tag to iterate through the objects in a list and delete the corresponding records in the database.

Example of a mapping file:

<delete id="deleteUsers" parameterType="java.util.List">
  DELETE FROM users WHERE id IN
  <foreach collection="list" item="id" open="(" close=")" separator=",">
    #{id}
  </foreach>
</delete>

Example Java code:

List<Integer> userIds = new ArrayList<>();
userIds.add(1);
userIds.add(2);
userIds.add(3);

sqlSession.delete("deleteUsers", userIds);

These examples demonstrate how to perform batch operations using lists in MyBatis. When using the foreach tag in the mapping file, the collection attribute specifies the parameter list to iterate over, the item attribute specifies the object name in each iteration, and the separator attribute specifies the separator between each object.

bannerAds