MyBatis中的foreach标签可以用来传入一个集合或数组类型的参数。以下是使用foreach标签传入数据的步骤:
<select id="selectUsers" resultType="User">
SELECT * FROM users WHERE id IN
<foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
#{item}
</foreach>
</select>
public interface UserMapper {
List<User> selectUsers(List<Integer> ids);
}
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUsers" resultType="User">
SELECT * FROM users WHERE id IN
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
</mapper>
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<Integer> ids = Arrays.asList(1, 2, 3);
List<User> userList = userMapper.selectUsers(ids);
在上述示例中,ids是一个包含1、2、3的List类型参数。foreach标签会将这个集合中的每个元素按照指定的方式进行拼接,最终生成SQL语句的IN条件。