foreach遍历集合
-
collection:指定要遍历的集合
-
list类型的参数会特殊处理封装在map中,map的key就叫list
-
item:将当前遍历出的元素赋值给指定的变量
-
#{变量名}就能取出变量的值也就是当前遍历出的元素
-
separator:每个元素之间的分隔符
-
open:遍历出所有结果拼接一个开始的字符
-
close:遍历出所有结果拼接一个结束的字符
-
index:索引。遍历list的时候 index就是索引
遍历map的时候index表示的就是map的key,item就是map的值
public List<Employee> getEmpsByConditionForeach(@Param("ids") List<Integer> ids);
<!-- public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> employee);-->
<select id="getEmpsByConditionForeach" resultType="com.atguigu.mybatis.bean.Employee">select * from tb1_employee<!--collection:指定要遍历的集合list类型的参数会特殊处理封装在map中,map的key就叫listitem:将当前遍历出的元素赋值给指定的变量#{变量名}就能取出变量的值也就是当前遍历出的元素separator:每个元素之间的分隔符open:遍历出所有结果拼接一个开始的字符close:遍历出所有结果拼接一个结束的字符index:索引。遍历list的时候 index就是索引遍历map的时候index表示的就是map的key,item就是map的值--><foreach collection="ids" item="item_id" separator="," open = "where id in (" close = ")">#{item_id}</foreach></select>
- 注意:这里的collection只能填list或者是map,如果想填ids,需要在参数上加@Param注解
@Testpublic void test02() throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();SqlSession sqlSession = sqlSessionFactory.openSession();try{EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);List<Employee> list = mapper.getEmpsByConditionForeach(Arrays.asList(1, 2, 3, 4));for (Employee emp : list){System.out.println(emp);}//手动提交数据sqlSession.commit();}finally {sqlSession.close();}}
foreach批量插入
- 方式一
public void addEmps(@Param("emps") List<Employee> emps);
<insert id="addEmps">INSERT INTO tb1_employee(last_name,email,gender,d_id)values<foreach collection="emps" item = "emp" separator=",">(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})</foreach></insert>
@Testpublic void test04() throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();SqlSession sqlSession = sqlSessionFactory.openSession();try{EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);List<Employee> emps = new ArrayList<>();emps.add(new Employee(null,"smitdash","smitadsh@qq.com","1",new Department(1)));emps.add(new Employee(null,"allsadasen","allesadn@qq.com","0",new Department(1)));mapper.addEmps(emps);sqlSession.commit();}finally {sqlSession.close();}}
- 方式二
这种方式需要数据库连接属性allowMultiQueries=true
dbconfig.properties:
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&allowMultiQueries=true
<insert id="addEmps"><foreach collection="emps" item = "emp" separator=";">INSERT INTO tb1_employee(last_name,email,gender,d_id)values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})</foreach></insert>