大众服务器网站,鸿邑网站建设,武威网站seo,苏州网站建设开发公司foreach遍历集合 collection:指定要遍历的集合 list类型的参数会特殊处理封装在map中#xff0c;map的key就叫list item:将当前遍历出的元素赋值给指定的变量 #{变量名}就能取出变量的值也就是当前遍历出的元素 separator:每个元素之间的分隔符 open:遍历出所有结果拼接一…foreach遍历集合 collection:指定要遍历的集合 list类型的参数会特殊处理封装在map中map的key就叫list item:将当前遍历出的元素赋值给指定的变量 #{变量名}就能取出变量的值也就是当前遍历出的元素 separator:每个元素之间的分隔符 open:遍历出所有结果拼接一个开始的字符 close:遍历出所有结果拼接一个结束的字符 index:索引。遍历list的时候 index就是索引 遍历map的时候index表示的就是map的keyitem就是map的值 public ListEmployee getEmpsByConditionForeach(Param(ids) ListInteger ids);!-- public ListEmployee getEmpsByConditionForeach(Param(ids)ListInteger employee);--
select idgetEmpsByConditionForeach resultTypecom.atguigu.mybatis.bean.Employeeselect * from tb1_employee!--collection:指定要遍历的集合list类型的参数会特殊处理封装在map中map的key就叫listitem:将当前遍历出的元素赋值给指定的变量#{变量名}就能取出变量的值也就是当前遍历出的元素separator:每个元素之间的分隔符open:遍历出所有结果拼接一个开始的字符close:遍历出所有结果拼接一个结束的字符index:索引。遍历list的时候 index就是索引遍历map的时候index表示的就是map的keyitem就是map的值--foreach collectionids itemitem_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);ListEmployee 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) ListEmployee emps);insert idaddEmpsINSERT INTO tb1_employee(last_name,email,gender,d_id)valuesforeach collectionemps item emp separator,(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})/foreach/insertTestpublic void test04() throws IOException {SqlSessionFactory sqlSessionFactory getSqlSessionFactory();SqlSession sqlSession sqlSessionFactory.openSession();try{EmployeeMapperDynamicSQL mapper sqlSession.getMapper(EmployeeMapperDynamicSQL.class);ListEmployee emps new ArrayList();emps.add(new Employee(null,smitdash,smitadshqq.com,1,new Department(1)));emps.add(new Employee(null,allsadasen,allesadnqq.com,0,new Department(1)));mapper.addEmps(emps);sqlSession.commit();}finally {sqlSession.close();}}方式二 这种方式需要数据库连接属性allowMultiQueriestrue
dbconfig.properties:
jdbc.urljdbc:mysql://localhost:3306/mybatis?serverTimezoneUTCallowMultiQueriestrueinsert idaddEmpsforeach collectionemps 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