歡迎您光臨本站 註冊首頁

MyBatis動態SQL foreach標籤實現批次插入的方法示例

←手機掃碼閱讀     hongdian2012 @ 2020-06-16 , reply:0

需求:查出給定id的記錄:

  SELECT * FROM tb1_emplyee WHERE id IN#{item_id}

 

關於foreach標籤,有幾個屬性應該注意一下:

  • collection:指定要遍歷的集合: 

  • list型別的引數會特殊處理封裝在map中,map的key就叫list 

  • item:將當前遍歷出的元素賦值給指定的變數 

  • separator:每個元素之間的分隔符 

  • open:遍歷出所有結果拼接一個開始的字元 

  • close:遍歷出所有結果拼接一個結束的字元 

  • index:索引。遍歷list的時候是index就是索引,item就是當前值 

  • 遍歷map的時候index表示的就是map的key,item就是map的值 

  • #{變數名}就能取出變數的值也就是當前遍歷出的元素 

測試方法:

  @Test     public void testDynamicSqlTest() throws IOException{       SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();       //1、獲取到的SqlSession不會自動提交資料       SqlSession openSession = sqlSessionFactoryopenSession();       try       {           EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass);           /*Employee employee=new Employee(1,"lili",null,"1");*/           Listemps=mappergetEmpsByConditionForeach(ArraysasList(1,2,3,4));           for (Employee e:emps){             Systemoutprintln(e);           }          }       finally {         openSessionclose();       }     }

 

foreach標籤也可以實現實現批次插入(刪除)資料:

這裡以批次插入資料為例:

  INSERT INTO tb1_emplyee(last_name,email,gender,d_id)       VALUES(#{emplastName},#{empemail},#{empgender},#{empdeptid})

 

對應的介面:

  public void addEmps(@Param("emps")Listemps);

 

測試方法
 

  @Test     public void testBatchSave() throws IOException{       SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();       //1、獲取到的SqlSession不會自動提交資料       SqlSession openSession = sqlSessionFactoryopenSession();       try       {         EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass);         Listemps=new ArrayList();         empsadd(new Employee(null,"Eminem","Eminem@com","1",new Department(1)));         empsadd(new Employee(null,"2Pac","2Pac@com","1",new Department(1)));         mapperaddEmps(emps);         openSessioncommit();       }       finally {         openSessionclose();       }      }

 

         


[hongdian2012 ] MyBatis動態SQL foreach標籤實現批次插入的方法示例已經有238次圍觀

http://coctec.com/docs/java/show-post-238760.html