MyBatis動態(tài)SQL foreach標簽實現(xiàn)批量插入的方法示例
需求:查出給定id的記錄:
<select resultType='comtestbeansEmployee'> SELECT * FROM tb1_emplyee WHERE id IN <foreach collection='list' item='item_id' separator=',' open='(' close=')'> #{item_id} </foreach> </select>
關(guān)于foreach標簽,有幾個屬性應該注意一下:
collection:指定要遍歷的集合: list類型的參數(shù)會特殊處理封裝在map中,map的key就叫l(wèi)ist item:將當前遍歷出的元素賦值給指定的變量 separator:每個元素之間的分隔符 open:遍歷出所有結(jié)果拼接一個開始的字符 close:遍歷出所有結(jié)果拼接一個結(jié)束的字符 index:索引。遍歷list的時候是index就是索引,item就是當前值 遍歷map的時候index表示的就是map的key,item就是map的值 #{變量名}就能取出變量的值也就是當前遍歷出的元素測試方法:
@Test public void testDynamicSqlTest() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); //1、獲取到的SqlSession不會自動提交數(shù)據(jù) SqlSession openSession = sqlSessionFactoryopenSession(); try { EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass); /*Employee employee=new Employee(1,'lili',null,'1');*/ List<Employee> emps=mappergetEmpsByConditionForeach(ArraysasList(1,2,3,4)); for (Employee e:emps){ Systemoutprintln(e); } } finally { openSessionclose(); } }
foreach標簽也可以實現(xiàn)實現(xiàn)批量插入(刪除)數(shù)據(jù):
這里以批量插入數(shù)據(jù)為例:
<insert id='addEmps'> INSERT INTO tb1_emplyee(last_name,email,gender,d_id) VALUES <foreach collection='emps' item='emp' separator=','> (#{emplastName},#{empemail},#{empgender},#{empdeptid}) </foreach> </insert>
對應的接口:
public void addEmps(@Param('emps')List<Employee> emps);
測試方法
@Test public void testBatchSave() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); //1、獲取到的SqlSession不會自動提交數(shù)據(jù) SqlSession openSession = sqlSessionFactoryopenSession(); try { EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass); List<Employee> emps=new ArrayList<Employee>(); 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(); } }
到此這篇關(guān)于MyBatis動態(tài)SQL foreach標簽實現(xiàn)批量插入的方法示例的文章就介紹到這了,更多相關(guān)MyBatis動態(tài)SQL foreach批量插入內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
