<select id="findCustomerByIds" parameterType="List" resultType="customer">
           select * from t_customer where id in
            <foreach item="id" index="index" collection="array" 
                            open="(" separator="," close=")">
                   #{id}
            </foreach>
</select>

代码 

目录

代码 


 当collection改成array时候  改成Integer[] array = new Integer[] {};

@Test
	public void findCustomerByIdsTest() throws Exception{
	
		SqlSession  sqlSession = MyBatisUtils.getSession();
//		List<Integer> ids = new ArrayList<Integer>();
//		ids.add(1);
//		ids.add(2);
		 Integer[] array = new Integer[] {1, 2, 3, 4};
		 List<Customer> customers =         
         sqlSession.selectList("com.wy.mapper.CustomerMapper.findCustomerByIds", array);
		
		 for(Customer customer : customers) {
			 System.out.println(customer);
		 }
		
		sqlSession.close();
	}

在 MyBatis 中,`<foreach>` 元素通常用于在 SQL 语句中迭代集合的元素。当 `collection` 属性的值是一个 List 类型时,`<foreach>` 会遍历 List 中的元素。如果你要遍历的是数组,需要将 `collection` 属性的值改为数组名。

以下是从 List 改为数组的示例:

假设原始的 SQL 语句是这样的:

```xml
<select id="selectUsersByIds" parameterType="java.util.List" resultType="User">
  SELECT * FROM users WHERE id IN
  <foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
    #{item}
  </foreach>
</select>
```

将其中的 `collection` 从 `ids`(List)改为 `array`(数组):

```xml
<select id="selectUsersByIds" parameterType="int[]" resultType="User">
  SELECT * FROM users WHERE id IN
  <foreach item="item" index="index" collection="array" open="(" separator="," close=")">
    #{item}
  </foreach>
</select>
```

在这个例子中,`parameterType` 设置为 `int[]` 表示传入的参数是一个整数数组。同时,`collection` 设置为 `array`,表示在 SQL 中使用数组进行迭代。

请根据你的实际情况调整参数类型、SQL 语句和其他属性。这只是一个简单的示例,实际场景可能需要根据具体情况进行更灵活的配置。

我的其他博客

HTTP与HTTTPS的区别-CSDN博客

什么情况下会产生StackOverflowError(栈溢出)和OutOfMemoryError(堆溢出)怎么排查-CSDN博客

谈谈我对HashMap扩容机制的理解及底层实现-CSDN博客

Redis 两种持久化方式 AOF 和 RDB-CSDN博客MySQL中的锁(简单)-CSDN博客

JDK、JRE、JVM的特点和关联-CSDN博客

面向对象的三大特征-CSDN博客

雪花算法生成id-CSDN博客

浅谈开源和闭源的认知-CSDN博客

浅谈开源和闭源的认知-CSDN博客

TCP三次握手 四次挥手-CSDN博客

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐