What is the method to pass a collection in MyBatis?
There are two main ways to pass collections in Mybatis: using a List or a Map.
- Passing collections using List: When defining a method in the Mapper interface, you can directly pass a List as a parameter, and Mybatis will automatically pass the elements in the List as parameters to the SQL statement. For example:
public List<User> selectUserByIds(List<Integer> ids);
You can use the foreach tag in the XML configuration file to iterate through List parameters, as shown below:
<select id="selectUserByIds" resultType="User">
SELECT * FROM user WHERE id IN
<foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
#{item}
</foreach>
</select>
- Passing collections using Map: Collections can be encapsulated as a Map and passed to SQL statements. When defining methods in the Mapper interface, you can pass in a Map as a parameter, where the key can be customized and the value is of collection type. For example:
public List<User> selectUserByIds(Map<String, Object> map);
In the XML configuration file, collection parameters can be accessed using the key of a Map, as shown below:
<select id="selectUserByIds" resultType="User">
SELECT * FROM user WHERE id IN
<foreach item="id" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
</select>
Both methods can effectively pass collection parameters to SQL statements, so choose the appropriate method based on the specific requirements in actual development.