collection:指定数组或者集合
item:代表数组或集合中的元素
separator:循环之间的分隔符
open:foreach循环拼接的所有sql语句的最前面以什么开始
close:foreach循环拼接的所有sql语句的最前面以什么结束
delete from t_car where id in(……)
/*** foreach标签 批量删除* @param ids* @return*/int deleteByIds(Long[] ids);
使用foreach标签时,collection这个属性的值应该是什么?
假设先使用接口中传进来的参数。
如果不想写where id in "()"这两个括号 可以使用open、close属性
delete from t_car where id in(#{id} )
运行测试程序会报错

分析报错原因:ids这个属性没找到
解决方法:1、collection=arg0;
2、ccollection=array
3、接口中的属性加注解@Param(“ids”) 建议使用这个注解的方式。
@Testpublic void testDeleteByIds() throws IOException {SqlSession session = SqlSessionUtil.openSession();CarMapper mapper = session.getMapper(CarMapper.class);Long[] ids ={12L,13L,15L};int count = mapper.deleteByIds(ids);System.out.println(count);session.commit();session.close();}
删除了3条数据

delete from t_car where id=1 or id=2 ……
separator 分隔符这个属性的值改为 or即可
delete from t_car whereid=#{id} )
一次向数据库表中插入多条记录。
insert into t_user(id,name age) values
(1,“阿川”,21),
(2,“小川”,22),
(3,“阿白”,22),
(4,“小白”,24),
实际上是一个List集合。
/*** 一次插入多条记录* @param cars* @return*/int insertBatch(@Param("cars") List cars);
insert into t_car values(null,#{car.carNum},#{car.brand},#{car.guidePrice},#{car.produceTime},#{car.carType})
@Testpublic void testInsertBatch() throws IOException {SqlSession session = SqlSessionUtil.openSession();CarMapper mapper = session.getMapper(CarMapper.class);Car car1 = new Car(null,"111","奔奔",32.0,"2022-11-14","代步车");Car car2 = new Car(null,"112","奥迪",62.0,"2022-10-14","新能源");Car car3 = new Car(null,"113","比亚迪",72.0,"2022-11-15","电车");Car car4 = new Car(null,"114","大众",82.0,"2022-11-10","电动车");Car car5 = new Car(null,"115","QQ",92.0,"2022-11-4","燃油车");List cars = new ArrayList<>();cars.add(car1);cars.add(car2);cars.add(car3);cars.add(car4);cars.add(car5);int count = mapper.insertBatch(cars);session.commit();session.close();System.out.println(count);}
5条记录插入成功

执行前:

执行后:

上一篇:C#图解教程(第四章)