<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 语句和其他属性。这只是一个简单的示例,实际场景可能需要根据具体情况进行更灵活的配置。
我的其他博客
什么情况下会产生StackOverflowError(栈溢出)和OutOfMemoryError(堆溢出)怎么排查-优快云博客