mybatis使用foreach遍历list集合或者array数组

时间:2025-03-20 07:23:40
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-////DTD Mapper 3.0//EN"
  "/dtd/">
<mapper namespace="com.mybatis_demo.">
<!-- 遍历list集合,collection="list",如果你传参的时候是直接传递list集合,那么这里只能填list,不能填参数名 -->
<select  resultType="User">
	select * from t_user where uid in
	<foreach collection="list" item="item" open="(" separator="," close=")">
		#{item}
	</foreach>
</select>
<!-- 遍历数组 ,collection="array",如果你传参的时候是直接传递数组,那么这里只能填array,不能填参数名-->
<select  resultType="User">
	select * from t_user where uid in
	<foreach collection="array" item="item" open="(" separator="," close=")">
		#{item}
	</foreach>
</select>
<!-- 遍历包装类中的数组,collection="ids",这里不再是array,而是包装类中对应的变量名,因为你传递的参数是一个包装类,mybatis是通过get方法获取包装类中的数组 -->
<select  parameterType="UserVo" resultType="User">
	select * from t_user where uid in
	<foreach collection="ids" item="item" open="(" separator="," close=")">
		#{item}
	</foreach>
</select>
<!-- 遍历包装类中的list集合,collection="idList",这里不再是list,而是包装类中对应的变量名,因为你传递的参数是一个包装类,mybatis是通过get方法获取包装类中的list集合 -->
<select  parameterType="UserVo" resultType="User">
	select * from t_user where uid in
	<foreach collection="idList" item="item" open="(" separator="," close=")">
		#{item}
	</foreach>
</select>
</mapper>