mybatis 批量插入 foreach
时间: 2023-10-14 16:05:10 浏览: 114
在MyBatis中,可以使用foreach标签来实现批量插入操作。foreach标签可以用于循环遍历集合或数组,并执行相应的SQL语句。以下是几个示例:
1. 使用foreach批量删除数据:
```
delete from xxx_table where id in <foreach collection="list" item="item" index="index" open="(" separator="," close=")"> #{item} </foreach> => (1,2,3,4)
```
2. 使用foreach批量插入数据:
```
<insert id="batchInsert">
insert into ref_teacher_course (teacher_id,course_id,create_time,update_time) values
<foreach collection="teacherCourseList.CourseList" item="item" index="index" separator=",">
(#{teacherCourseList.username}, #{item}, #{teacherCourseList.create_time}, #{teacherCourseList.update_time})
</foreach>
</insert>
```
3. 在Mapper接口中定义批量保存方法:
```
@Mapper
public interface UserMapper {
void batchSave(List<User> userList);
}
```
4. 使用foreach批量保存数据:
```
<insert id="batchSave">
<foreach collection="list" item="user" separator=";">
insert into user(name, password) values (#{user.name}, #{user.password})
</foreach>
</insert>
```
在测试类中调用批量保存方法:
```
@RunWith(SpringRunner.class)
@SpringBootTest
public class SbMybatis02ApplicationTests {
@Test
public void testBatchSave(){
User user1 = new User();
user1.setName("关羽");
user1.setPassword("guanyu");
User user2 = new User();
user2.setName("张飞");
user2.setPassword("zhangfei");
List<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);
userMapper.batchSave(userList);
}
}
```
以上就是使用MyBatis中的foreach实现批量插入的示例。使用foreach可以简化批量操作的编写,提高效率。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [Mybatis批量添加(foreach标签)](https://blog.csdn.net/m0_51212267/article/details/121641252)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [MyBatis 使用 foreach 批量插入](https://blog.csdn.net/lizhengyu891231/article/details/125546407)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文