在Mybatis中传递集合的方法主要有两种方式:使用List或者使用Map。
- 使用List传递集合:在Mapper接口中定义方法时,可以直接传入List作为参数,Mybatis会自动将List中的元素作为参数传递给SQL语句。例如:
publicList<User>selectUserByIds(List<Integer>ids);
在XML配置文件中,可以使用foreach标签来遍历List参数,如下所示:
<selectid="selectUserByIds"resultType="User">
SELECT*FROMuserWHEREidIN
<foreachitem="item"index="index"collection="ids"open="("separator=","close=")">
#{item}
</foreach>
</select>
publicList<User>selectUserByIds(Map<String,Object>map);
在XML配置文件中,可以通过Map的key来获取集合参数,如下所示:
<selectid="selectUserByIds"resultType="User">
SELECT*FROMuserWHEREidIN
<foreachitem="id"collection="ids"open="("separator=","close=")">
#{id}
</foreach>
</select>
这两种方式都可以有效地传递集合参数给SQL语句,在实际开发中根据需求选择合适的方式。