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 id="deleteByIds">
delete from t_car where id in(
<foreach collection="ids" item="id" separator=",">
#{id}
foreach>
)
delete>
运行测试程序会报错
分析报错原因:ids这个属性没找到
解决方法:1、collection=arg0;
2、ccollection=array
3、接口中的属性加注解@Param(“ids”) 建议使用这个注解的方式。
@Test
public 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();
}
delete from t_car where id=1 or id=2 ……
separator 分隔符这个属性的值改为 or即可
<delete id="deleteByIds">
delete from t_car where
<foreach collection="ids" item="id" separator="or">
id=#{id}
foreach>
)
delete>
一次向数据库表中插入多条记录。
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<Car> cars);
<insert id="insertBatch">
insert into t_car values
<foreach collection="cars" item="car" separator=",">
(null,#{car.carNum},#{car.brand},#{car.guidePrice},#{car.produceTime},#{car.carType})
foreach>
insert>
@Test
public 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<Car> 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);
}