Passing List in MyBatis: Methods and Examples

MyBatis offers several methods for passing in a List.

  1. Passing in multiple values as a parameter using a List. In the method of the Mapper interface, you can directly use a List as a parameter, and use a foreach loop in the SQL statement to iterate through the values in the List.
public interface UserMapper {
    List<User> getUserList(List<String> ids);
}
<select id="getUserList" parameterType="java.util.List">
    SELECT * FROM users WHERE id IN
    <foreach item="item" collection="list" separator="," open="(" close=")">
        #{item}
    </foreach>
</select>
  1. Pass multiple values by using an array as a parameter. Similar to List, just replace List with an array.
public interface UserMapper {
    List<User> getUserList(String[] ids);
}
<select id="getUserList" parameterType="java.lang.String[]">
    SELECT * FROM users WHERE id IN
    <foreach item="item" collection="array" separator="," open="(" close=")">
        #{item}
    </foreach>
</select>
  1. Pass multiple values as parameters using a wrapper class. Define a wrapper class to encapsulate the multiple values and use this wrapper class as a parameter in the Mapper interface method.
public class IdListWrapper {
    private List<String> ids;

    // getter and setter
}

public interface UserMapper {
    List<User> getUserList(IdListWrapper idListWrapper);
}
<select id="getUserList" parameterType="com.example.IdListWrapper">
    SELECT * FROM users WHERE id IN
    <foreach item="item" collection="ids" separator="," open="(" close=")">
        #{item}
    </foreach>
</select>

All of these methods can achieve the function of passing in a List, so just choose the method that suits your specific requirements.

bannerAds