<!-- 【foreach标签】 collection:设置要循环的数组或集合 item:用一个字符串表示数组或集合中的每一个数据 separator:设置每次循环的数据之间的分隔符 open:循环的所有内容以什么开始 close:循环的所有内容以什么结束 -->
mapper接口
public interface EmpMapper { int batchAddEmps(@Param("emps") List<Emp> emps); int batchDelEmps(@Param("empIds") Integer[] empIds); }
mapper.xml-批量添加
<insert id="batchAddEmps"> insert into t_emp values <foreach collection="emps" item="emp" separator=","> (null,#{emp.empName},#{emp.age},#{emp.gender},null) </foreach> </insert>
批量添加测试代码:
@Test public void testAddEmps(){ SqlSession sqlSession = SqlSessionUtil.getSqlSession(); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); Emp emp1 = new Emp(null,"小明1",20,"男"); Emp emp2 = new Emp(null,"小明2",21,"男"); Emp emp3 = new Emp(null,"小明3",22,"男"); List<Emp> list = Arrays.asList(emp1, emp2, emp3); int res = mapper.batchAddEmps(list); System.out.println(res); }
mapper.xml-批量删除(方法一)
<delete id="batchDelEmps"> delete from t_emp where emp_id in ( <foreach collection="empIds" item="id" separator=","> #{id} </foreach> ) </delete>
测试代码:
@Test public void testDelEmps(){ SqlSession sqlSession = SqlSessionUtil.getSqlSession(); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); Integer[] ids = new Integer[]{5,6,7}; int res = mapper.batchDelEmps(ids); System.out.println(res); }
mapper.xml-批量删除(方法二)
<delete id="batchDelEmps"> delete from t_emp where <foreach collection="empIds" item="id" separator="or"> emp_id = ${id} </foreach> </delete>
标签:mapper,批量,Emp,标签,EmpMapper,emp,mybatis,null,foreach From: https://www.cnblogs.com/ixtao/p/17177302.html