MyBatis中的foreach標簽可以用來傳入一個集合或數(shù)組類型的參數(shù)。以下是使用foreach標簽傳入數(shù)據(jù)的步驟:
<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類型參數(shù)。foreach標簽會將這個集合中的每個元素按照指定的方式進行拼接,最終生成SQL語句的IN條件。