foreach-遍歷集合 -筆記要點
<!--foreach 遍歷標簽 collection : 指定要遍歷的集合; list類型的參數會特殊處理封裝在Map中,map的key就叫做list; item ; 將當前遍歷的元素復制給指定的變量; separator : 每個元素之間的分隔符! open : 遍歷出所有的結果拼接到一個開始的字符! close: 遍歷出所有的結果拼接一個 結束的字符! index : 索引,遍歷list的時候是索引, 遍歷map的時候index表示的就是map的key,item就是map的值; #{變量名},就能取出變量的值,也就是當前遍歷出的元素 -->
出錯分析與總結
1.定義接口
//查詢員工id'在給定集合中的 public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);
2.定義XML映射文件
<!--public List<Employee> getEmpsByConditionForeach(Employee e);--> <select id="getEmpsByConditionForeach" resultType="com.bean.Employee"> select * from tbl_employee -- where id in (1,5,6) <foreach collection="ids" item="item_id" separator="," open="where id in (" close=")" index=""> #{item_id} </foreach> </select>
3.編寫測試代碼
public SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); } @Test public void test11() throws Exception { SqlSession openSession = getSqlSessionFactory().openSession(); try { System.out.println("++++++++++---- 1.測試 動態SQL元素:foreach!"); EmployeeMapper_DynamicSQL mapper = openSession.getMapper(EmployeeMapper_DynamicSQL.class); List<Employee> list = mapper.getEmpsByConditionForeach(Arrays.asList(1, 2, 3, 4)); for(Employee e:list) System.out.println(e); openSession.commit(); } finally { openSession.close(); } }
測試結果:
++++++++++---- 1.測試 動態SQL元素:foreach! DEBUG 12-05 16:25:49,085 ==> Preparing: select * from tbl_employee -- where id in (1,5,6) where id in ( ? , ? , ? , ? ) (BaseJdbcLogger.java:145) DEBUG 12-05 16:25:49,104 ==> Parameters: 1(Integer), 2(Integer), 3(Integer), 4(Integer) (BaseJdbcLogger.java:145) DEBUG 12-05 16:25:49,106 <== Total: 2 (BaseJdbcLogger.java:145) Employee{id=1, lastName='Jerry2333', email='233@...', gender='1', dept=null} Employee{id=4, lastName='葫蘆娃', email='葫蘆娃@163.com', gender='0', dept=null}